2012-08-10 93 views
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-memberbool的非标准转换?

+0

请参阅[为什么模板参数推演不适用于此?](http://stackoverflow.com/questions/1268504/why-is-the-template-argument-deduction-not-working-here?lq=1 ) – 2012-08-10 11:39:17

+1

是否有任何理由不能使用'template std :: ostream&operator <<(std :: ostream&,const Test &);'? – juanchopanza 2012-08-10 11:42:32

回答

4

typename Test<T>::unspecifiedT处于非可推论上下文,因为它似乎一个::的左侧。因此,您的功能模板甚至不会被考虑,并且转换为unspecified被用作唯一可行的过载。

简短的回答很简单,就是“模板不能像那样工作”。让我知道你是否想要更长的答案。

+0

是的,对不起...不,我不需要很长的回答。 – ForEveR 2012-08-10 11:40:05

+0

说“实际的参数类型是**'**'的** right **,这会阻止'::'左边的模板参数'T'推断出来。“?即阻碍是嵌套类型不参与推论。 – TemplateRex 2012-08-10 12:04:34