作为模板非类型参数的 C 字符串在 gcc 6.3 中有效,但在 Visual Studio 2017(x64 为 19

C string as template non-type parameter works in gcc 6.3 but does not work in Visual Studio 2017 (19.16.27027.1 for x64)

本文关键字:但在 Visual 有效 2017 x64 Studio 类型参数 gcc 字符串      更新时间:2023-10-16

以下代码:

#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 跳过的错误?

有人有更漂亮的解决方案吗?

可以改用对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;
}

这在Visual Studio中使用MSVC编译。

这是有效的,因为根据 Cpp首选项,允许将带有链接的命名左值引用作为非类型参数。(请注意,hello不是本地的。

相关文章: