带有std :: string的Literal类只适用于模板特化?

时间:2014-12-28 20:43:05

标签: c++ templates c++11

我的编译器不允许使用以下定义,因为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}}

模板允许此定义的类型是什么?

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构造函数。 [...]