C++中是否存在错误类型
Is there an error type in 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++的类型系统中有错误类型吗?如果没有,我能意识到吗?
否,语言或标准库没有提供此类类型。如果你愿意,欢迎你自己制作:
template <typename T>
struct error { };
另一种选择是简单地从基本模板中省略type
定义。当T1
、T2
和T3
的值与这两个专业化中的任何一个都不匹配时,您将获得没有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"
中-请参阅本线程。
相关文章:
- 我的模板类方法返回错误类型?
- 错误:类型"double()"和"double()"的操作数无效到二进制&quo
- 类型为 "int*" 的参数与 C++ 中错误类型"int**"参数不兼容
- glDrawElements GL 错误类型 = 0x824c,严重性 = 0x9146,消息 = GL_INVALID
- Eclipse/CDT_C++给出"语义错误_"类型XXX无法解决"。项目运行
- turbo 为什么我的C++代码中出现错误类型名称预期"错误?
- "auto"推断出 hashtable_policy.h 中的错误类型
- 设计自己的结果/两者之一:是否应该始终指定成功类型和错误类型
- 如何修复"ctypes"。参数错误:参数 2:<键入"异常.类型错误">:RaspberryPi 中的错误类型"错误
- 在 vscode 上编译错误.类型说明符是 C++11 扩展
- 不允许使用错误类型
- 当读取错误类型时,CIN覆盖我的初始化值
- C++:"错误:类型'const char*'和'const char [28]'的操作数无效到二进制'ope
- 我的代码错误类型警告 1 警告 C4018 和更多错误
- 在shared_from_this()中的错误类型(在继承类中)(是否有dyn.type-ware shared Poi
- 为什么缩小转换范围不能防止错误类型的map.insert()失败
- 程序总是返回二进制'>>':找不到运算符,它采用错误类型的左操作数
- 错误:类型为 '.&' 来自类型的临时 '..*康斯特'
- 涉及将要馈送的向量转换为execvp的错误类型
- C++中是否存在错误类型