我有一些类型,其中每个类型都有相同名称的子类型:
struct TypeA {
typedef int subtype;
};
struct TypeB {
typedef float subtype;
};
以及没有此子类型但在同一上下文中使用的类型:
struct TypeC {
// (no subtype defined)
};
如何添加一个虚拟子类型来提供自定义编译错误消息?
我的(到目前为止不成功的)尝试是:
struct TypeC {
struct subtype {
static_assert(false, "Attempt to access the non-existent subtype of TypeC.");
};
};
But static_assert(false, ...)
无法工作,因为即使从未访问过该类型,编译器也会抛出错误。
怎样才能延迟评估static_assert
到访问类型的时间?
失败的尝试是引入一个虚拟枚举并从中构造一个表达式:
enum { X };
static_assert(X != X, "...");
具体用例:我有一个类模板List
这是用子类型定义的head
and tail
如果非空,并且如果为空则使用这些子类型应该给出错误:
template<typename...>
struct List;
// empty list:
template<>
struct List<> {
struct head { static_assert(false, "Attempt to access the head of an empty list."); };
struct tail { static_assert(false, "Attempt to access the tail of an empty list."); };
};
// non-empty list:
template<typename Head, typename ...Tail>
struct List<Head, Tail...> {
typedef Head head;
typedef List<Tail...> tail;
};
如果我简单地省略类型head
and tail
,当访问例如大小为 2 的列表的第 3 个元素,代码为List<int,int>::tail::tail::head
给出了不太好的消息(g++ 4.7.2):'head' is not a member of 'List<int>::tail {aka List<>}'