user108088
user108088

Reputation: 1168

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

Upvotes: 11

Views: 2837

Answers (1)

Timmmm
Timmmm

Reputation: 96586

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

Upvotes: 3

Related Questions