【问题标题】:Is there an error type in C++?C++ 中是否存在错误类型?
【发布时间】:2012-07-09 21:05:23
【问题描述】:

考虑以下类型

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

【问题讨论】:

  • 听起来你可能想要std::enable_if
  • @Flexo 嗯...我已经检查过它以及 C++11 中的 std::conditional 和 std::is_same 。但我真的需要我的函数明确告诉它卡住了:-(

标签: c++ types


【解决方案1】:

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

template <typename T>
struct error { };

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

【讨论】:

  • 所以没有办法让我的函数判断类型是否可以接受?
  • 编译器已经告诉你了。如果可以接受,编译器将继续编译程序的其余部分。如果不可接受,它会显示类似“没有foo 的版本接受该类型”。一些编译器会说明可接受的类型是什么,但这通常是在处理重载而不是模板时。通过重载,存在有限数量的可能性,因此编译器可以将它们全部打印出来。使用模板,更难了解所有可能性。在这种情况下,好的文档比技术解决方案更容易。
  • 有时使用的技巧是产生更好的错误消息,例如 typedef typename T1::____THIS_TYPE_DOES_NOT_WORK type;
  • @Rob 你是对的。使用 MS VS2012,即使智能感知也能分辨。谢谢。
【解决方案2】:

怎么样:

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 线程。

【讨论】:

    猜你喜欢
    • 2011-06-16
    • 1970-01-01
    • 2018-08-04
    • 2012-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多