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算法的本地类
显然,“无链接”意味着“该名称只能从其所在的范围内引用”。包括局部变量。这些在模板参数中无效,因为它们的地址显然在编译时未知。
简单的解决方案是将其设为全局变量。它并没有真正改变你的代码。
另请参阅https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52036
| 归档时间: |
|
| 查看次数: |
1280 次 |
| 最近记录: |