检查const char *作为非类型模板参数

时间:2018-11-11 18:34:57

标签: c++

使用msvc 14,我想将const char *参数检查为非类型模板参数。

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();

由于错误C2131,以下代码无法编译:声明时,static_assert(Key != nullptr, "may be not null")上的表达式未求值为常量 Base<int, A_STRING>

如果可能的话,我不想使用包装器:

template <const char *str>
class Str {
};

Base<int, Str<A_STRING> > test;
[...]

有没有办法使之成为可能?

1 个答案:

答案 0 :(得分:1)

正如Matthieu所说,只有(并且只有)您进行更改时,这才有效:

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

收件人:

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

Live Demo

相关问题