문제

More templated woes... I love C++, but sometimes I hate it.

I cannot figure out why the compiler is complaining here, and what I can do about it.

struct blah
{
   template<class t>
   blah(void(*)(t), t){}
};

void Func(int i) {}
void Func2(int& i) {}

void test()
{
   int i = 3;
   blah b(Func, i);   
   blah b2(Func2, i);        //error C2660: 'blah::blah' : function does not take 2 arguments
   blah b3(Func2, (int&)i);  //error C2660: 'blah::blah' : function does not take 2 arguments

}

What is going on here?

I am using MSVC2008.

도움이 되었습니까?

해결책

The other answers explain what's going on: when template argument deduction finds two ways to deduce a template argument, it looks at each alone and they all must agree exactly.

You can probably get this class working the way you intended by making sure the second use of t is in a "non-deduced context":

template<typename T>
struct identity { typedef T type; };

struct blah
{
   template<class t>
   blah(void(*)(t), typename identity<t>::type){}
};

This way when the blah constructor is called, C++ will deduce t from the function pointer, but won't try to deduce it from the second argument. The type deduced then gets substituted in both places.

다른 팁

In MSVC 2012 Intellisense says (roughly transleted):

1 IntelliSense: No instances of constructor ""blah::blah"" is matching the list of arguments.

Argument types are: (void (int &i), int)

@mfontanini is correct and you have a deduction problem here.

You could add a second constructor

template<class t>
blah(void(*)(t), t){}
template<class t>
blah(void(*)(t&), t&){}

If you compile the same snippet on gcc, you get a more intuitive error message:

test.cpp:14:20: note:   deduced conflicting types for parameter ‘t’ (‘int&’ and ‘int’)

The compiler is deducing that the template parameter t is int& for the first parameter, and int for the second one. Since these are different types, you get a compilation error.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top