C++中是否存在错误类型

Is there an error type in C++?

本文关键字:错误 类型 存在 是否 C++      更新时间:2023-10-16

考虑以下类型的

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++的类型系统中有错误类型吗?如果没有,我能意识到吗?

否,语言或标准库没有提供此类类型。如果你愿意,欢迎你自己制作:

template <typename T>
struct error { };

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

怎么样:

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>

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