1

考虑以下类型

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++ 类型系统中是否存在错误类型?如果没有,我可以实现它还是如何实现?

4

2 回答 2

4

不,语言或标准库没有提供这种类型。如果您愿意,欢迎您自己制作:

template <typename T>
struct error { };

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

于 2012-07-09T21:12:16.717 回答
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"-请参阅线程。

于 2012-07-09T21:27:53.763 回答