c模板化构造函数错误

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

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

  1. struct blah
  2. {
  3. template<class t>
  4. blah(void(*)(t),t){}
  5. };
  6.  
  7. void Func(int i) {}
  8. void Func2(int& i) {}
  9.  
  10. void test()
  11. {
  12. int i = 3;
  13. blah b(Func,i);
  14. blah b2(Func2,i); //error C2660: 'blah::blah' : function does not take 2 arguments
  15. blah b3(Func2,(int&)i); //error C2660: 'blah::blah' : function does not take 2 arguments
  16.  
  17. }

这里发生了什么?

我正在使用MSVC2008.

解决方法

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

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

  1. template<typename T>
  2. struct identity { typedef T type; };
  3.  
  4. struct blah
  5. {
  6. template<class t>
  7. blah(void(*)(t),typename identity<t>::type){}
  8. };

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

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