2016-05-12 38 views
1

假设我有一个功能:有没有办法给std :: conditional fail更好的错误?

template<typename T, typename Dummy = 
          typename std::enable_if<std::is_integral<T>::value,int>::type > 
void foo(T var0, T var1); 

如果T是一些整数类型此功能仅创建。唯一的问题是,如果我尝试在非整数类型上使用它,我会得到这个巨大的错误。

有没有什么办法来创建一个类似的情况下发生的自定义错误字符串?

+0

其实,你的例子甚至不工作对我来说:http://coliru.stacked-crooked.com/a/edfd2163b75a8b12 –

+0

@BaummitAugen这将失败,因为双打都没有积分 – DarthRubik

+0

我拿到那是应该发生,但gcc和clang不会发生这种情况。 Tbh,我不知道为什么。如果你关心,可能值得一个额外的问题。 –

回答

3

刚落假把戏和使用static_assert,这就像一本教科书的用例:

#include <type_traits> 

template <class T> 
void fun(T t){ 
    static_assert(std::is_integral<T>::value, "fun requires integral"); 
} 

int main(){ 
    fun(1); 
    fun(2.); 
} 

失败了比较明确的信息:

main.cpp: In instantiation of 'void fun(T) [with T = double]': 
main.cpp:10:11: required from here 
main.cpp:5:5: error: static assertion failed: fun requires integral 
    static_assert(std::is_integral<T>::value, "fun requires integral"); 
    ^~~~~~~~~~~~~ 

在一些或多或少遥远的未来2020年或者你也可以使用concepts来实现这一点,如果你想要玩这个,在gcc中有一个实验性的实现。

相关问题