Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 Local static values not working as template arguments

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

like image 202
user108088 Avatar asked Nov 17 '14 06:11

user108088


People also ask

Can template have default parameters?

Template parameters may have default arguments. The set of default template arguments accumulates over all declarations of a given template.

How to instantiate a template function c++?

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.

What is a template argument c++?

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.


1 Answers

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

like image 152
Timmmm Avatar answered Nov 11 '22 21:11

Timmmm