c++ - 作为模板非类型参数的 C 字符串适用于 gcc 6.3,但不适用于 Visual Studio 2017(19.16.27027.1 for x64)

标签 c++ visual-studio templates

以下代码:

#include <iostream>

template<const char* Pattern> void f() {
    std::cout << Pattern << "\n";
}

static constexpr const char hello[] = "Hello";

int main() {
    f<hello>(); //Microsoft (R) C/C++ Optimizing Compiler Version 19.16.27027.1 for x64
    //  Copyright (C) Microsoft Corporation.  All rights reserved.
    //
    //  string-as-template-parameter.cpp
    //  string-as-template-parameter.cpp(10): fatal error C1001: An internal error has occurred in the compiler.
    //  (compiler file 'msc1.cpp', line 1518)
    //   To work around this problem, try simplifying or changing the program near the locations listed above.
    //  Please choose the Technical Support command on the Visual C++
    return 0;
}

在 gcc (g++ (Debian 6.3.0-18+deb9u1) 6.3.0 20170516) 编译时有效,但在 VS 2017 编译时结果为 C1001。

作为解决方法,我使用:

#include <iostream>

template<const char** Pattern> void f() {
    std::cout << *Pattern << "\n";
}

static const char* hello = "Hello";

int main() {
    f<&hello>();
    return 0;
}

有人知道更漂亮的解决方案吗?可能是初始代码有一个被 gcc 跳过的错误?

最佳答案

Does anybody have idea of more beautiful solution?

您可以使用对 std::string 的引用。

#include <iostream>
#include <string>

template<std::string & Pattern> void f() {
    std::cout << Pattern << "\n";
}

static std::string hello = "Hello";

int main() {
    f<hello>(); 
    return 0;
}

这与 MSVC in Visual Studio 编译.

这是可行的,因为根据 Cppreference , 带链接的命名左值引用被允许作为非类型参数。 (注意 hello 不是本地的。)

关于c++ - 作为模板非类型参数的 C 字符串适用于 gcc 6.3,但不适用于 Visual Studio 2017(19.16.27027.1 for x64),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55472023/

相关文章:

c++ - 清除屏幕上的特定位置

c++ - 如何安全地关闭其中有无限循环的线程

c++ - 多个 %lu 来格式化 ULONG64

c# - 我无法在 XAML 文件中写入阿拉伯文本

c# - 为什么 "Paste JSON As Classes"和 "Paste XML As Classes"命令在 Visual Studio 中被禁用(灰显)?

javascript - 从另一个网站导入 <template> 元素

c++ - 为什么这个 CRTP 不能编译?

c++ - 强制 C++ 程序在 Visual Studio 调试器中暂停

vb.net - 链接到其他类的地址?

c++ - 为什么 C+ +'s ` 变量模板的行为不符合预期?