在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;
}
在GCC 4.9.0中,代码错误
error: ‘myStr’ is not a valid template argument of type ‘const char*’ because ‘myStr’ has no linkage
在Clang 3.4.1中,代码错误
candidate template ignored: invalid explicitly-specified argument for template parameter 'Str'
两个编译器都使用-std = c ++ 11
运行指向在线编译器的链接,您可以从中选择众多C ++编译器之一:http://goo.gl/a2IU3L
注意,在myStr
之外移动main
会编译并按预期运行。
注意,我已经查看了类似于C ++ 11之前的StackOverflow问题,并且大多数表明这应该在C ++ 11中解决。例如Using local classes with STL algorithms
答案 0 :(得分:0)
显然,“无链接”意味着"The name can be referred to only from the scope it is in."包括局部变量。这些在模板参数中无效,因为它们的地址在编译时显然是未知的。
简单的解决方案是使其成为全局变量。它并没有真正改变你的代码。