作为模板非类型参数的C字符串在gcc 6.3中有效,但在Visual Studio 2017中不起作用(对于x64为19.16.27027.1)

问题描述 投票:6回答:1

以下代码:

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

c++ visual-studio templates
1个回答
5
投票

有没有人想到更漂亮的解决方案?

您可以使用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不是本地的。)

© www.soinside.com 2019 - 2024. All rights reserved.