c模板化构造函数错误

前端之家收集整理的这篇文章主要介绍了c模板化构造函数错误前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
更模糊的困境……我喜欢C,但有时我讨厌它.

我无法弄清楚为什么编译器在这里抱怨,以及我能做些什么呢.

@H_404_4@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 }

这里发生了什么?

我正在使用MSVC2008.

解决方法

其他答案解释了发生了什么:当模板参数推导找到两种推导模板参数的方法时,它会单独查看每个参数,并且它们都必须完全一致.

你可以通过确保第二次使用t在“非推导的上下文”中来使这个类按照你预期的方式工作:

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

这样当调用blah构造函数时,C将从函数指针中推导出t,但不会尝试从第二个参数中推导出它.推导出的类型然后在两个地方被替换.

原文链接:https://www.f2er.com/c/116665.html

猜你在找的C&C++相关文章