考虑一个在运行时只包装一个值的类:
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;
};
以及它的 constexpr 版本:
template <typename Type>
class ConstValue
{
public:
constexpr ConstValue(const Type& val) : _value(val) {;}
constexpr Type get() const {return _value;}
protected:
const Type _value;
};
问题1:你能确认constexpr版本的设计方式是正确的吗?
问题 2:如何将这两个类混合到一个名为 Value 的类中,它可以是 constexpr 构造的或运行时构造的,其值可以是 get( ) 在运行时还是编译时?
编辑:
问题 3:如果 get() 定义在 .cpp 文件中,如果我希望 get() 被内联,如果它不是constexpr 函数的正确声明是什么?是吗
constexpr inline Type get();
或
inline constexpr Type get()
还是别的什么?
最佳答案
只需将 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;
};
你不需要 const 和 non-const 版本,因为这可以通过实例化模板 Value 来完成常量 或非常量 类型。
您不需要constexpr 和非constexpr 版本,constexpr 意味着潜在的常量表达式表达式是否最终成为一个常量表达式取决于它的参数。表达式是否最终在编译时 求值取决于上下文和实现。
关于c++ - constexpr 类的设计 : merging constexpr and non-constexpr versions?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14390848/