我有一個模板化的類,我正試圖為一個嵌套的列舉創建一個字串。
如果我將operator<<代碼直接行內到類的主體中,我可以讓它編譯和作業,但我試圖將它放在一個單獨的impl.hpp檔案中,以利于閱讀。
但是,我無法讓它編譯。看起來這應該是可行的,但我在C 所要求的語法上犯了難。
這里有一個演示問題的小例子,同時還有一個實時鏈接。https://godbolt.org/z/6cMn8Gf14
#include <iostream>
使用 std::cout。
using std::endl;
template <class T>
struct Foo {
enum class State {
X,Y,Z
};
//這個版本的作業原理是:
/*
friend std::ostream& operator<<(std::ostream &os, State s) {
return os << "stringify state..."。
*/
//這個版本失敗了--見main()中的完整錯誤。
template <class T2>
friend std::ostream& operator<<(std::ostream &os, typename Foo<T2> :State s) 。
};
template <class T>
std::ostream& operator<<(std::ostream &os, typename Foo<T> ::State s) {
return os << "stringify state..."/span>。
}
int main()
{
auto x = Foo<int> ::State::X;
/*
錯誤:與'operator<<'不匹配 ...
細節。
注意:候選:'template<class T> std::ostream& operator<<(std::ostream&, typename Foo<T> :State)'
std::ostream& operator<<(std::ostream &os, typename Foo<T>:State s) {
^~~~~~~~
注意:模板引數推導/替換失敗。
注:無法推匯出模板引數'T'。
cout << "X: " << x << endl;
^
*/
cout << "X: " << x << endl;
return 0;
}
這應該怎么寫?
uj5u.com熱心網友回復:
這里的朋友函式就是這樣。非模板函式由類模板印出。 因此,沒有辦法大規模地定義它們,盡管你可以定義個別的版本,比如
std::ostream& operator<<(std::ostream &os, Foo<int> :State s) {...}
std::ostream& operator<<(std::ostream &os, Foo<float>:state s) {...}
由于你不能從Foo<T>::State推匯出T,這是你唯一的實作選擇。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/315765.html
標籤:
