I can't seem to use local static values as template arguments, in C++11. For example:
#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;
}
In GCC 4.9.0, the code errors with
error: ‘myStr’ is not a valid template argument of type ‘const char*’ because ‘myStr’ has no linkage
In Clang 3.4.1, the code errors with
candidate template ignored: invalid explicitly-specified argument for template parameter 'Str'
Both compilers were run with -std=c++11
A link to an online compiler where you can select one of many C++ compilers: http://goo.gl/a2IU3L
Note, moving myStr
outside main
compiles and runs as expected.
Note, I have looked at similar StackOverflow questions from before C++11, and most indicate that this should be resolved in C++11. For example Using local classes with STL algorithms
Template parameters may have default arguments. The set of default template arguments accumulates over all declarations of a given template.
To instantiate a template function explicitly, follow the template keyword by a declaration (not definition) for the function, with the function identifier followed by the template arguments. template float twice<float>(float original); Template arguments may be omitted when the compiler can infer them.
A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.
Apparently "no linkage" means "The name can be referred to only from the scope it is in." including local variables. Those aren't valid in template parameters because their address isn't known at compile time apparently.
Easy solution is to make it a global variable. It doesn't really change your code.
See also https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52036
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With