正如问题所暗示的,我想做的是
template<const char* Err>
struct broken
{
template<typename... Args>
constexpr broken(Args&&...)
{
//the sizeof... confuses the compiler as to only emit errors when instantiated
//this does not work, static_assert only accepts string literals
static_assert(sizeof...(Args) < 0, Err);
}
};
我希望 broken
在实例化时发出编译器错误消息 Err
。但是,static_assert
只接受一个字符串文字作为它的第二个参数。有什么方法可以根据 constexpr
字符串发出编译器错误?
最佳答案
你想要的东西不可能以任何形式或形式起作用,因为你可以合法地做
extern const char foo[];
template <const char* err> class broken {};
broken<foo> tisbroken;
和 foo
甚至不需要在当前 TU(或其他任何地方)中定义就可以编译。
foo
中 err
的 ODR 使用会在 foo
未定义时导致链接器错误,但为时已晚.
所以不,您不能使用传递给模板的字符串来打印编译器消息,因为没有字符串。
关于c++ - 使用 constexpr C 字符串作为编译器错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43618964/