考虑一个在运行时只包装了一个值的类:
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;
};以及它的常量表达式版本:
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()还是别的什么?
发布于 2013-01-18 08:59:56
只需将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;
};您不需要常量和非常量版本,因为这可以通过使用常量或非常量类型实例化模板Value来完成。
你不需要常量表达式和非常量表达式版本,constexpr意味着潜在的常量表达式,表达式最终是否是常量表达式取决于它的参数。表达式最终是否会在编译时被计算取决于上下文和实现。
发布于 2013-01-18 09:00:42
您的constexpr类的设计是正确的,除了您输入了错误的构造函数名称(它应该是ConstValue,而不是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;
};
int main(int argc, char* argv[])
{
int x[ConstValue<int>(3).get()];
}https://stackoverflow.com/questions/14390848
复制相似问题