禁止运营商<<调用

时间:2012-08-10 11:28:34

标签: c++ templates operator-overloading

我有一些代码。

#include <iostream>

template<typename T>
struct Test
{
   Test(bool v):flg(v) { }
   void func() { }
   typedef void (Test::*unspecified)();
   operator unspecified() const
   {
      return flg ? &Test::func : 0;
   }
   bool flg;
};

template<typename T>
std::ostream& operator << (std::ostream&, typename Test<T>::unspecified);

int main()
{
   Test<int> t(true);
   std::cout << t << std::endl;
}

输出

1

它工作正常,但我想得到未定义的引用。如果Testnot template class,我会得到未定义的引用。那么,为什么编译器不使用operator <<作为函数类型并从pointer to class-memberbool进行标准转换?

1 个答案:

答案 0 :(得分:4)

typename Test<T>::unspecified中,T位于不可导入的上下文中,因为它显示在::的左侧。因此,您的功能模板甚至从未被考虑过,转换为unspecified被用作唯一可行的过载。

简短的回答就是“模板不能像那样工作”。如果您想要更长的答案,请告诉我。

相关问题