我想使用模板類的嵌套類型實現模板函數。使用模板類的嵌套類型作爲模板參數
我剛剛讀了here,最好是將operator <<
作爲非會員和非朋友功能。因此,我決定搬到外面MyClass
功能toStream()
和tableToStream()
:
template <typename T>
class MyClass
{
public:
typedef boost::dynamic_bitset<> BoolTable;
typedef std::vector<T> MsgTable;
private:
BoolTable b_;
MsgTable m_;
public:
const BoolTable& getB() const { return b_; }
const MsgTable & getM() const { return m_; }
std::ostream& toStream (std::ostream& os) const
{
os <<"Bool: "; tableToStream (os, getB()); os <<'\n';
os <<"Msg:"; tableToStream (os, getM()); os <<'\n';
return os;
}
template <typename TABLE>
std::ostream& tableToStream (std::ostream& os, const TABLE& table) const
{
for (int i=0; i < table.size(); ++i)
os << table[i] <<',';
return os;
}
};
template <typename T>
std::ostream& operator << (std::ostream& os, const MyClass<T> mc)
{
return mc.toStream(os);
}
這很容易MyClass::toStream()
轉換爲operator <<
非會員和非友元函數:
template <typename T>
std::ostream& operator << (std::ostream& os, const MyClass<T>& mc)
{
os <<"Bool: "; mc.tableToStream (os, mc.getB()); os <<'\n';
os <<"Msg:"; mc.tableToStream (os, mc.getM()); os <<'\n';
return os;
}
但我想用完全operator <<
而不是致電MyClass::tableToStream()
:
template <typename T>
std::ostream& operator << (std::ostream& os, const MyClass<T>& mc)
{
os <<"Bool: "<< mc.getB() <<'\n';
os <<"Msg:" << mc.getM() <<'\n';
return os;
}
對於功能MyClass::tableToStream()
我可以使用以下實現,但這可能會混淆流輸出,因爲該函數過於通用(任何類型都可能是TABLE
)。
template <typename TABLE>
std::ostream& operator << (std::ostream& os, const TABLE& table)
{
for (int i=0; i < table.size(); ++i)
os << table[i] <<',';
return os;
}
因此,我想限制到嵌套類型的MyClass
。下面是我嘗試MyClass::tableToStream()
轉換成標準operator <<
非成員和非友元函數的一個:
template <typename T, typename MyClass<T>::TABLE>
std::ostream& operator << (std::ostream& os, const TABLE& table)
{
for (int i=0; i < table.size(); ++i)
os << table[i] <<',';
return os;
}
但誤差約爲typename MyClass<T>::TABLE
。
是否流(OS)需要一個模板參數?它通常只是std :: ostream。 – 2013-02-20 14:50:30
你原來的'toStream()'不會引用'MyClass'中的任何內容,甚至不會引用'MsgTable'。目前還不清楚你想要達到的目標。你確定'TABLE'應該是'toStream()'的模板參數嗎? – Angew 2013-02-20 14:58:08
@VaughnCato,OS也可以是std :: ofstream或任何其他輸出流。請參閱後http://stackoverflow.com/questions/236801/should-operator-be-implemented-as-a-friend-or-as-a-member-function/237111#237111乾杯;-) – olibre 2013-02-20 15:22:59