我的编译器不允许使用以下定义,因为std::string
有一个非平凡的析构函数(有意义的是teststr
当成员没有时,class teststr
{
private:
std::string _m;
public:
constexpr teststr(std::string value) : _m(value) {};
constexpr std::string m() const { return _m; }
void m(std::string value) { _m = value; }
};
不能有一个微不足道的dtor :
teststr
但是,允许以下等同(据我所知)template<typename T>
class test
{
private:
T _m;
public:
constexpr test(T value) : _m(value) {};
constexpr T m() const { return _m; }
void m(T value) { _m = value; }
};
typedef test<std::string> teststr;
的定义:
{{1}}
模板允许此定义的类型是什么?
答案 0 :(得分:5)
constexpr
,因为在模板定义时通常不知道成员是否满足constexpr
的要求。当模板成员被声明为constexpr
时,在模板实例化时确定constexpr
是否合适,如果不合适,则以静默方式删除。
鉴于
template <typename T> struct test {
T val;
constexpr test(T val) : val(val) { }
};
你可以
constexpr test<int> i = 3;
因为使用T = int
,构造函数符合constexpr
的要求,但您不能拥有
constexpr test<string> s = "";
因为 构造函数不符合constexpr
的要求。
实例化test<string>
并不是一个难事,因为这会严重限制在模板中使用constexpr
的能力。
从标准(C ++ 11):
7.1.5 constexpr说明符[dcl.constexpr]
6如果
constexpr
函数模板的实例化模板特化或类模板的成员函数无法满足constexpr
函数或constexpr
构造函数的要求,则该特化是不是constexpr
函数或constexpr
构造函数。 [...]