0

using msvc 14, i would like to check a const char* argument as a non-type template argument.

template <typename T, const char Key[] = nullptr > class Base { public: Base() {} void f_not_null() { static_assert(Key != nullptr, "may be not null"); } void f_null() { static_assert(Key == nullptr, "may be null"); } }; extern const char A_STRING[] = "a string"; Base<int, A_STRING> test; test.f_not_null(); Base<int> test1; test1.f_null(); 

The code below does not compile due to error C2131: expression did not evaluate to a constant on static_assert(Key != nullptr, "may be not null") when declaring Base<int, A_STRING>.

If possible I would not like to use a wrapper as a workaround:

template <const char *str> class Str { }; Base<int, Str<A_STRING> > test; [...] 

Is there a way to make this possible?

1
  • If your variable is extern, why is it declared here? Commented Nov 11, 2018 at 18:45

1 Answer 1

1

As Matthieu says, this will work if (and only if) you change:

extern const char A_STRING[] = "a string"; 

to:

static const char A_STRING[] = "a string"; 

Live Demo

Sign up to request clarification or add additional context in comments.

3 Comments

Unfortunately, i m not using gcc, i use msvc 14 and this does not work and fall into error C2971: 'Base': template parameter 'Key': 'A_STRING': a variable with non-static storage duration cannot be used as a non-type argument which is why i've used extern.
my code sample is a brief sample of a code using extern on a const char* declared into another compilation unit and is set to use a static storage duration with external linkage.
Yes, you're right, MSVC won't compile the code I posted, see: rextester.com/DUZQB23817. I would call that an MSVC bug, since both gcc and clang are perfectly happy and the error message produced by MSVC makes no sense. I think you are stuck here.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.