2012-08-10 90 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