C++ 模板类型检查参数C++;,不同类型的执行路径

C++ 模板类型检查参数C++;,不同类型的执行路径,c++,templates,C++,Templates,我希望模板中的逻辑根据模板参数略有不同。如何键入检查模板参数 我有以下几点,但令人惊讶的是,它们不起作用: 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(); } }

我希望模板中的逻辑根据模板参数略有不同。如何键入检查模板参数

我有以下几点,但令人惊讶的是,它们不起作用:

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();
  }
}
类栏{
Bar(){}
}
样板
void Foo(施工及测试a){
如果(!std::is_same::value){
//对类型栏执行可能失败的操作,例如。
a、 失败();
}
}
不希望使用模板专门化,因为在现实中,模板专门化最终会为我的特定目的共享大量代码(当前工作的代码正在使用模板专门化)


当前,在编译过程中此操作失败:
“Bar”中的“no member”Fail
不是专门化整个模板函数
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.
}
模板
无效FooHelper(常数T&a){
a、 失败();
}
样板
void FooHelper(常数条和a){
//除了a.fail()之外的东西
}
样板
void Foo(施工及验收){
食物助理(甲);;
//等等等等。
}

每个分支都应该对每种类型有效。
在C++17中,可以使用if 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();
  }
}
模板
void Foo(施工及测试a){
如果constexpr(!std::is_same::value){
//对类型栏执行可能失败的操作,例如。
a、 失败();
}
}
以前,你必须依赖专业化或过载。 例如

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);
    // ...
}
模板
void Fail(const T&T){T.Fail();}
无效失败(常数条&){/*空*/}
样板
void Foo(施工及测试a){
// ...
不合格(a);
// ...
}

Template specialization是正确的解决方案。有用的提示:“Template specialization”并不意味着“复制整个巨大的函数,只是为了更改其中的一小部分”。在C++11中是否有其他方法可以实现同样的概念?您可以查看。