2012-07-09 71 views
1

考虑以下几种类型C++中是否存在错误类型?

template <typename T1, typename T2, typename T3> 
struct either_or 
{ 
    /* Here I need such an error type that says "Sorry, T1 is not an accepting type." */ 
    typdef error<T1> type; 
}; 
template <typename T1, typename T3> 
struct either_or <T1, T1, T3> 
{ 
    typedef T1 type; //T1 Ok 
}; 
template <typename T1, typename T2> 
struct either_or <T1, T2, T1> 
{ 
    typedef T1 type; //T1 Ok 
}; 

/* Here is function that might accept error type variable */ 

template <typename T> 
void foo(typename either_or<T, char, unsigned char>::type x) 
{ 
    /*print char or unsigned char except that T is not printable*/ 
} 

是否有C++的类型系统错误类型在这种情况下使用?如果没有,我能否意识到它或如何?

+0

听起来像你可能想'std :: enable_if' – Flexo 2012-07-09 21:06:32

+0

@Flexo嗯......我已经检查了它以及std :: conditional和std :: is_same在C++ 11中。但是我真的需要我的函数来明确地告诉它它是什么:-( – Yang 2012-07-09 21:10:50

回答

4

不,没有这样的语言或标准库提供的类型。欢迎你来弥补自己的,如果你想:

template <typename T> 
struct error { }; 

另一种选择是简单地忽略基本模板的type定义。当T1,T2T3的值与两种专业化中的任何一种不匹配时,您将获得基本模板,该模板将不具有type成员。这会导致编译器不考虑foo的版本,并且当您尝试使用无效参数类型调用它时,最终会得到编译错误。

+0

所以我没有办法让我的函数知道这个类型是可接受的还是不正确的? – Yang 2012-07-09 21:15:51

+0

编译器已经告诉你,如果可以接受的话,编译器继续编译程序的其余部分,如果不可接受,则表示类似于“foo”没有接受该类型的版本。“有些编译器会说可接受的类型是什么,但通常在处理重载时,而不是模板,因为重载,可能性有限,因此编译器可以全部打印它们,使用模板很难知道所有的可能性,这是一个好的文档比技术解决方案更容易的情况。 – 2012-07-09 21:18:33

+0

A有时候使用的技巧是导致一个更好的错误消息,像这样 typedef typename T1 :: ____ THIS_TYPE_DOES_NOT_WORK type; – 2012-07-09 21:23:12

1

如何:

template <typename T1, typename T2, typename T3> 
struct either_or 
{ 
    static_assert(false, "Sorry but this doesn't work for type T1"); 
    //typdef error<T1> type; 
}; 
template <typename T1, typename T3> 
struct either_or <T1, T1, T3> 
{ 
    typedef T1 type; //T1 Ok 
}; 
template <typename T1, typename T2> 
struct either_or <T1, T2, T1> 
{ 
    typedef T1 type; //T1 Ok 
}; 

/* Here is function that might accept error type variable */ 

template <typename T> 
void foo(typename either_or<T, char, unsigned char>::type x) 
{ 
    /*print char or unsigned char except that T is not printable*/ 
} 

这应该显示是这样的:

error: Sorry but this doesn't work for type T1 
when instantiating either_or<T1,T2,T3> 
with T1 = <typename>, T2=<typename>, T3=<typename> 

如果编译 - 确切的错误信息将取决于课程的编译器。如果您想问 - 不,则不可能将实际类型名称集成到消息"Sorry but this doesn't work for type T1"中 - 请参阅this线程。