我的编译器不允许使用以下定义,因为std::string
它具有非平凡的析构函数(在teststr
没有成员的情况下不能有平凡的dtor是有意义的):
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; }
};
但是,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;
模板化允许该定义的类型是什么?
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
构造函数。[...]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句