Vin*_*ent 10 c++ constructor const constexpr c++11
考虑一个只在运行时包装值的类:
template <typename Type>
class NonConstValue
{
public:
NonConstValue(const Type& val) : _value(val) {;}
Type get() const {return _value;}
void set(const Type& val) const {_value = val;}
protected:
Type _value;
};
Run Code Online (Sandbox Code Playgroud)
和constexpr版本:
template <typename Type>
class ConstValue
{
public:
constexpr ConstValue(const Type& val) : _value(val) {;}
constexpr Type get() const {return _value;}
protected:
const Type _value;
};
Run Code Online (Sandbox Code Playgroud)
问题1:您能否确认constexpr版本是否以正确的方式设计?
问题2:如何将两个类混合成一个名为Value可以constexpr构造或运行时构造的类,其值可以get()在运行时或编译时?
编辑:问题3:如果get()在.cpp文件中定义,如果我想get()内联,如果它不是一个constexpr正确的函数声明?是吗
constexpr inline Type get();
Run Code Online (Sandbox Code Playgroud)
要么
inline constexpr Type get()
Run Code Online (Sandbox Code Playgroud)
或者是其他东西 ?
K-b*_*llo 20
只需将说明constexpr符添加到每个可能的常量表达式函数中.
template <typename Type>
class Value
{
public:
constexpr Value(Type const& val) : _value(val) {}
constexpr Type const& get() const {return _value;}
void set(Type const& val) {_value = val;}
protected:
Type _value;
};
Run Code Online (Sandbox Code Playgroud)
你并不需要一个常量和非const版本,因为这可以通过实例化模板来完成Value一个常量或非const类型.
您不需要constexpr和非constexpr版本,constexpr意味着潜在的常量表达式以及表达式最终是否为常量表达式取决于其参数.表达式是否最终在编译时被评估取决于上下文和实现.