【发布时间】:2013-01-01 16:28:53
【问题描述】:
考虑一个只在运行时包装一个值的类:
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函数可以在编译时或运行时调用。 -
我认为非静态
constexpr成员函数存在缺陷,因为它们总是暗示const函数限定符,即constexpr foo bar();与constexpr foo bar() const;声明相同。对非成员没有这样的要求,即constexpr foo bar(T&);或constexpr foo bar(T&&);可以都接受非constT(并且可以有涉及非const 限定类类型的常量表达式)。所以要小心。
标签: c++ c++11 constructor constants constexpr