2015-03-30 73 views
1

我有以下代碼...調用專門的ostream操作

#include <sstream> 

enum class eTag 
{ 
    A, 
    B, 
    C 
}; 

template<eTag I> std::ostream& operator<< (std::ostream& str, int i) 
{ 
    return str; // do nothing 
} 

template<> std::ostream& operator<< <eTag::A>(std::ostream& str, int i) 
{ 
    return str << "A:" << i; // specialize for eTag::A 
} 

template<> std::ostream& operator<< <eTag::B>(std::ostream& str, int i) 
{ 
    return str << "B:" << i; // specialize for eTag::B 
} 

template<> std::ostream& operator<< <eTag::C>(std::ostream& str, int i) 
{ 
    return str << "C:" << i; // specialize for eTag::C 
} 

int main() 
{ 
    std::ostringstream s; 

    // s << <eTag::A>(42) << std::endl; 

    return 0; 
} 

這編譯。但是從main()的註釋行中可以看到,我正在爲如何實際調用ostream操作符的專門化而苦惱。

+0

可能重複的是它不可能手動調用C++操作符?](http://stackoverflow.com/questions/7225962/is-it-not-possible-to-call-c-operators-manually) – Pradhan 2015-03-30 21:22:44

+1

雖然可怕,但運營商<< (std :: cout,42)<< std :: endl;'。我更好奇*爲什麼*你想這樣做。 ' – WhozCraig 2015-03-30 21:24:09

+1

@Pradhan不是真的很愚蠢,對吧?正如你所關聯的問題主要是關於爲基本類型重載'operator +'。 – vsoftco 2015-03-30 21:30:46

回答

1

快速回答:

operator<< <eTag::A>(std::cout,42); 

我覺得你有實現自己的模板類用操縱朋友ostream& operator<<(ostream&)好得多,並保持狀態作爲成員變量(通過構造函數初始化)。見here(除了模板的一部分)

1
operator<<<eTag::A>(std::cout, 42) << std::endl; 

(如果你願意,你可以添加和模板參數列表operator<<之間的空間。不有所作爲。)

這是非常討厭。通常我們不會編寫需要顯式模板參數的操作符。好做這樣的事情:

inline std::ostream& operator<<(std::ostream& os, eTag x) { 
    if (x == eTag::A) { 
     return os << "A:"; 
    } else if (x == eTag::B) { 
     return os << "B:"; 
    } else if (x == eTag::C) { 
     return os << "C:"; 
    } else { 
     throw std::range_error("Out of range value for eTag"); 
    } 
} 

然後:

std::cout << eTag::A << 42 << std::endl; 

A good compiler will be able to inline this,所以,如果你剛剛輸入

std::cout << "A:" << 42 << std::endl; 
你的代碼將被視爲有效的[
+0

不錯,我在這裏看到的唯一問題是'throw'永遠不會執行。如果你通過其他任何東西而不是標籤,那麼'std''運算符<<'踢進來了。我明白了,如果你有一個更大的'enum',它會發生... – vsoftco 2015-03-30 21:42:35

+0

@vsoftco你可以把它看作是一個守衛如果有人向enum添加更多標籤並忘記更新'operator <<'。 – Brian 2015-03-30 21:51:18

+0

的確,好點! – vsoftco 2015-03-30 21:51:52