[英]C++ template question
有沒有辦法實現指定的行為? 如果有一些技巧或者可以使用traits或enable_if
來完成,請告訴我。
template <typename T> struct Functional {
T operator()() const {
T a(5);
// I want this statement to be tranformed into
// plain 'return;' in case T = void
return a; // <---
}
};
int main() {
Functional<int> a;
a();
Functional<void> b;
b(); // <--- Compilation error here
}
只是專注於虛空:
template <typename T> struct Functional {
T operator()() const {
T a(5);
return a;
}
};
template <> struct Functional<void> {
void operator()() const {
}
};
只需說以下內容即可。 它非常適用於T
void
並且相當於您顯示的代碼
T operator()() const {
return static_cast<T>(5);
}
你可以使用專業化
template <> struct Functional<void> {
void operator()() const {
}
};
這應該工作
template <> struct Functional<void> //specialized for 'void'
{
void operator()() const {
//do something
return ; //optional
}
};
編輯:
你也可以寫(更簡單的方法)
T operator()() const {
return T(5); // static_cast<> not even required
}
此代碼存在比首次出現的問題更嚴重的問題。 例如,如果你要將Functional的返回值轉發給另一個函數,那么你不能只將函數聲明為void - 整個批次必須被指定為void,因為如果你有一個無效的函數,你可以傳遞給它一個無效的表達。 當然,你不能用void等創建變量。 總的來說,更容易說虛空是非法的,而不是試圖處理它。
還有其他答案已經有明確的專業化答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.