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

I cannot 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, 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, code errors with

 candidate template ignored: invalid explicitly-specified argument for template parameter 'Str' 

Both compilers were launched with -std = C ++ 11

Link to the online compiler where you can choose one of the many C ++ compilers: http://goo.gl/a2IU3L

Note. Moving myStr outside main is done by compilation and is done as expected.

Note. I looked at similar StackOverflow issues prior to C ++ 11, and most of them indicate that this should be allowed in C ++ 11. For example, using local classes with STL algorithms

+8
source share
1 answer

Apparently, "lack of binding" means "The name can only be indicated from the area in which it is located." including local variables. They are not valid in the template parameters because their address is unknown at compile time.

A simple solution is to make it global. It really does not change your code.

See also https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52036

+1
source

Source: https://habr.com/ru/post/978270/


All Articles