[英]Invoking specialized ostream operator
我有以下代碼...
#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運算符的特殊化。
快速回答:
operator<< <eTag::A>(std::cout,42);
我認為,實現自己的模板類操縱器要好得多,該操縱器將ostream& operator<<(ostream&)
用作朋友,並將狀態保留為成員變量(通過構造函數初始化)。 參見此處 (模板部分除外)
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;
一個好的編譯器將能夠內聯該代碼,因此您的代碼將像您剛剛鍵入的代碼一樣高效。
std::cout << "A:" << 42 << std::endl;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.