1

我有一些代码。

#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-memberto进行标准转换bool

4

1 回答 1

4

In typename Test<T>::unspecified,T是在一个不可演绎的上下文 中,因为它出现在 a 的左侧::。因此,您的函数模板甚至不会被考虑,并且转换unspecified为唯一可行的重载。

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

于 2012-08-10T11:34:36.853 回答