c++ - 使用 constexpr C 字符串作为编译器错误消息

标签 c++ compiler-errors

正如问题所暗示的,我想做的是

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(或其他任何地方)中定义就可以编译。

fooerr 的 ODR 使用会在 foo 未定义时导致链接器错误,但为时已晚.

所以不,您不能使用传递给模板的字符串来打印编译器消息,因为没有字符串

关于c++ - 使用 constexpr C 字符串作为编译器错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43618964/

相关文章:

c++ - Visual Studio 2015 : v120 vs v140?

c++ - 为什么具有返回类型但不返回任何内容的函数不会编译失败?

c++ - 非事件 #ifdef block 中的编译器错误

c++ - 我可以从命令行编写和编译所有类型的 Visual Studio 应用程序吗?

c++ - GCC 不将 __VA_ARGS__ 视为宏中的参数

c++ - 如何通过鼠标移动而不是 VK_SPACE 打开显示

c++ - Eclipse 报错 127

c++ - 跳棋程序的设计

c++ - 内联调用 always_inline 失败 '__m128i _mm_cvtepu8_epi32(__m128i)' : target specific option mismatch _mm_cvtepu8_epi32 (__m128i __X)

Android Studio 集成测试无法解析符号 AndroidJUnit4