[英]Template type check parameter C++, different type execution paths
我想要基於template參數的模板中的邏輯稍有不同。 如何輸入檢查模板參數?
我有以下令我驚訝的行不通的方法:
class Bar {
Bar() {}
}
template <typename T>
void Foo(const &T a) {
if (!std::is_same<T, Bar>::value) {
// Do things that will fail for type Bar e.g.
a.Fail();
}
}
我不希望使用模板專業化,因為實際上模板專業化最終會出於我的特定目的共享很多代碼(當前有效的代碼正在使用模板專業化)
當前,這在編譯過程中失敗: "no member "Fail" in "Bar"
與其專門化整個模板函數Foo
,不如專門化一個輔助方法:
template <typename T>
void FooHelper(const T &a) {
a.fail();
}
template <>
void FooHelper<Bar>(const Bar &a) {
// something other than a.fail()
}
template <typename T>
void Foo(const T &a) {
FooHelper<T>(a);
// etc. etc.
}
每個分支對於每種類型均應有效。
在C ++ 17中,可以使用constexpr來更改它:
template <typename T>
void Foo(const &T a) {
if constexpr (!std::is_same<T, Bar>::value) {
// Do things that will fail for type Bar e.g.
a.Fail();
}
}
在此之前,您必須依靠專業化或重載。 例如
template <typename T>
void Fail(const T& t) { t.Fail(); }
void Fail(const Bar&) { /*Empty*/ }
template <typename T>
void Foo(const &T a) {
// ...
Fail(a);
// ...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.