vendredi 7 décembre 2018

Different c++ compiler behavior when looking for overloaded vs. templated functions

I have been learning templates and trying to do some programming with it. Recently, I stumbled on a strange behavior which I try to summarize here. Suppose we have the following header file MyHeader.H

class Dit{...};
class B{...};
class A{
   ...
   B & operator[] (Dit & it){...};
   ...
 };

template <T> bar(T& t){

static_assert(!std::is_same(T,A)::value," in bar, T cannot be of type A");
...
};

and a main function

include "MyHeader.H"
foo(B & b){...};
foo(int t){...};
int main() {
A a;
Dit it;
foo(a[it]); // the compiler has no problem in selecting the right overloaded foo
bar(a[it]); // the compiler tries to instantiated it with type A, and because of the static_assert, it fails. 
return 0;
}

Why does the compiler looks for a bar(A a) definition, given that a[it] is of type B? I have not tried it yet, but would it make a difference if I used

bar<B>(a[it]);

instead? Of course, if I do

B & temp=a[it];
bar(temp); 

everything compiles fine.

Aucun commentaire:

Enregistrer un commentaire