[英]Template type check parameter C++, different type execution paths
I'd like slightly different logic in a template based on the template parameter. 我想要基于template参数的模板中的逻辑稍有不同。 How might I type check a template parameter? 如何输入检查模板参数?
I have the following which I am surprised does not work: 我有以下令我惊讶的行不通的方法:
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();
}
}
I do not wish to use template specialization as in reality template specialization ends up sharing a lot of code for my specific purpose (currently working code is using template specialization) 我不希望使用模板专业化,因为实际上模板专业化最终会出于我的特定目的共享很多代码(当前有效的代码正在使用模板专业化)
Currently this fails during compile: "no member "Fail" in "Bar"
当前,这在编译过程中失败: "no member "Fail" in "Bar"
Rather than specializing the entire template function Foo
, specialize a helper method: 与其专门化整个模板函数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.
}
Each branch should be valid for every type. 每个分支对于每种类型均应有效。
In C++17, you could use if constexpr which change that: 在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();
}
}
Before, you have to rely on specialization or overload. 在此之前,您必须依靠专业化或重载。 As for example 例如
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.