2017-09-12 31 views
-1

我想在基于模板参数的模板中略有不同的逻辑。我该如何键入检查模板参数?模板类型检查参数C++,不同类型的执行路径

我有我很惊讶以下不工作:

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"

+1

模板专门化是正确的解决方案。有用的提示:“模板专业化”并不意味着“重复整个庞大的功能,只是改变其中的一小部分”。 –

回答

4

每个分支应该对每个类型都有效。
在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); 
    // ... 
} 
+0

有没有另一种方法可以在C++ 11中实现这个相同的概念? –

+0

您可以查看[constexpr-if-alternative](https://stackoverflow.com/questions/43587405/constexpr-if-alternative)。 – Jarod42

4

而不是专门整个模板功能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. 
}