C++ 11本地静态值不作为模板参数

use*_*088 8 c++ templates c++11

在C++ 11中,我似乎无法使用本地静态值作为模板参数.例如:

#include <iostream>
using namespace std;

template <const char* Str>
void print() {
  cout << Str << endl;
}

int main() {
  static constexpr char myStr[] = "Hello";
  print<myStr>();
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

在GCC 4.9.0中,代码错误

error: ‘myStr’ is not a valid template argument of type ‘const char*’ because ‘myStr’ has no linkage
Run Code Online (Sandbox Code Playgroud)

在Clang 3.4.1中,代码错误

candidate template ignored: invalid explicitly-specified argument for template parameter 'Str'
Run Code Online (Sandbox Code Playgroud)

两个编译器都使用-std = c ++ 11运行

指向在线编译器的链接,您可以从中选择众多C++编译器之一:http://goo.gl/a2IU3L

注意,移动myStr到外部main编译并按预期运行.

注意,我已经查看了类似于C++ 11之前的StackOverflow问题,并且大多数表明这应该在C++ 11中解决.例如,使用具有STL算法的本地类

Tim*_*mmm 3

显然,“无链接”意味着“该名称只能从其所在的范围内引用”。包括局部变量。这些在模板参数中无效,因为它们的地址显然在编译时未知。

简单的解决方案是将其设为全局变量。它并没有真正改变你的代码。

另请参阅https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52036

  • 上面的代码是根据原始上下文进行简化的。在我的实际代码中,我有一个创建两行的宏:const 字符串和函数调用。宏不能创建全局变量和局部函数调用。 (3认同)
  • @BЈовић 如果这是 gcc 中的一个错误,那么我预计另一个独立生产的编译器不太可能有相同的错误。Clang 也不编译代码。 (2认同)