When two functions are exactly the same (except for const), which one gets called?

I'm grading a CS class in my school. So someone wrote this


1
2
3
4
5
  template <class T>
  Vector {
     T & operator[](int index) const;
     T & operator[](int index);
   }



So if I were in main, would there even be a way for me to distinguish which one is called? Which one gets called if I input

1
2
  Vector<int> v1;
   v1[0] = 3;
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <iomanip>

struct test
{
    void foo() { std::cout << "void test::foo()\n" ; }
    void foo() const { std::cout << "void test::foo() const ****\n" ; }
};

test rvalue() { return {} ; }
const test const_rvalue() { return {} ; }
test& lvalue() { static test t ; return t ; }
const test& const_lvalue() { static test t ; return t ; }

#define call_foo(x) ( (std::cout << std::setw(30) << #x << " => "), (x).foo() )

int main()
{

    test object ;
    call_foo(object) ; 

    const test const_object{} ;
    call_foo(const_object) ; 

    test& reference_to_object = object ;
    call_foo(reference_to_object) ; 

    const test& reference_to_const_object = object ;
    call_foo(reference_to_const_object) ; 

    call_foo( rvalue() ) ; 

    call_foo( const_rvalue() ) ; 

    call_foo( lvalue() ) ; 

    call_foo( const_lvalue() ) ; 
}

                        object => void test::foo()
                  const_object => void test::foo() const ****
           reference_to_object => void test::foo()
     reference_to_const_object => void test::foo() const ****
                      rvalue() => void test::foo()
                const_rvalue() => void test::foo() const ****
                      lvalue() => void test::foo()
                const_lvalue() => void test::foo() const ****

http://coliru.stacked-crooked.com/a/f13a5222c5358606
Topic archived. No new replies allowed.