Tys*_*obs 6 c++ templates reference template-argument-deduction
更模糊的困境......我喜欢C++,但有时我讨厌它.
我无法弄清楚为什么编译器在这里抱怨,以及我能做些什么呢.
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
}
Run Code Online (Sandbox Code Playgroud)
这里发生了什么?
我正在使用MSVC2008.
其他答案解释了发生了什么:当模板参数推导找到两种推导模板参数的方法时,它会单独查看每个参数,并且它们都必须完全一致.
你可以通过确保第二次使用t是在"非推断的上下文"中来使这个类按照你预期的方式工作:
template<typename T>
struct identity { typedef T type; };
struct blah
{
template<class t>
blah(void(*)(t), typename identity<t>::type){}
};
Run Code Online (Sandbox Code Playgroud)
这样,当blah调用构造函数时,C++将从t函数指针推导出,但不会尝试从第二个参数推导出它.推导出的类型然后在两个地方被替换.
| 归档时间: |
|
| 查看次数: |
364 次 |
| 最近记录: |