lweiiii
lweiiii

Reputation: 21

c++ template argument deduce

Q1:

template  <typename  T> void print(const T &) {cout("INT &");}
template  <typename  T> void print( T  ) {cout("INT");}

int main() {
    int i = 10;
    print(i);
}

complier saied "error: call of overloaded 'print(int&)' is ambiguous"

why?

is "const T &" and "T" are the same?

Q2:

template <typename T> void f( T){cout("F-T");};
template <typename T> void f( const T*){cout("F-T*");};
int main() {
    int ix = 43, *p=&ix;
    const int ci = 0, *p2 = &ci;
    f(p); // why result is "F-T"?
}

p is the pointer,and non-const can cast const.

why f(p) choose f( T)?

Upvotes: 1

Views: 42

Answers (1)

Caleth
Caleth

Reputation: 62531

For question 1: both overloads are equally "good" with T both deduced as int. It is an error to have a call where there is not a "best" overload. You get the same with

void print(const int &) { std::cout << "const int &"; }
void print(int) { std::cout << "int"; }

For question 2: The first overload, with T deduced int *, is a better than the second, with T deduced as int.

Upvotes: 1

Related Questions