Consider a class that just wraps a value at runtime :
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;
};
and the constexpr version of that:
template <typename Type>
class ConstValue
{
public:
constexpr ConstValue(const Type& val) : _value(val) {;}
constexpr Type get() const {return _value;}
protected:
const Type _value;
};
Question 1 : Can you confirm that the constexpr version is designed in the right way ?
Question 2 : How do you mix both classes into a single one called Value that can be constexpr constructed or runtime constructed and whose value can be get() at runtime or compile-time ?
EDIT :
Question 3 : If get() is defined in a .cpp file, and if I want get() to be inlined if it’s not a constexpr what is the right declaration of the function ? Is it
constexpr inline Type get();
or
inline constexpr Type get()
or something else ?
Just add the
constexprspecifier to each of those functions that are potential constant expressions.You don’t need a const and a non-const version, since that can be done by instantiating the template
Valuewith a const or non-const type.You don’t need a constexpr and a non-constexpr version,
constexprmeans potential constant expression and whether the expression ends up being a constant expression or not depends on its arguments. Whether or not the expression ends up being evaluated at compile-time depends on the context and the implementation.