【发布时间】:2014-08-28 13:31:08
【问题描述】:
我正在尝试定义具有用户定义类型的非类型模板参数的模板类。不幸的是,到目前为止还没有成功。真正的代码有点太长了,但是一个简化的例子是这样的:
#include <iostream>
template <class T>
class Maybe {
bool is_ = false;
T value_;
public:
constexpr Maybe() = default;
constexpr Maybe(T value) : is_(true), value_(value) {}
constexpr bool is() const { return is_; }
};
template <Maybe<int> parm>
struct Test {
void say() const {
std::cout << "parm is " << (parm.is() ? "set" : "not set") << ".\n";
}
};
int main() {
Test<Maybe<int>{}> not_set;
Test<Maybe<int>(2)> is_set;
not_set.say();
is_set.say();
}
当我尝试编译此代码(使用 Clang 3.4)时,我收到以下错误消息:
test.cc:15:22: error: a non-type template parameter cannot have type
'Maybe<int>'
template <Maybe<int> parm>
^
test.cc:23:10: error: value of type 'Maybe<int>' is not implicitly
convertible to 'int'
Test<Maybe<int>{}> not_set;
^~~~~~~~~~~~
test.cc:24:10: error: value of type 'Maybe<int>' is not implicitly
convertible to 'int'
Test<Maybe<int>(2)> is_set;
^~~~~~~~~~~~~
3 errors generated.
现在,我知道非类型模板参数必须满足some conditions。但是,我认为constexpr 就足够了。还是真的只能是内置的整数类型之一?
有没有办法传递我自己的用户定义类型的非类型模板参数?
【问题讨论】:
标签: c++ templates c++11 constexpr