Suppose I have a template class
template <typename T>
class foo {
T m;
decltype(auto) f() { return m.f(); }
};
How can I give foo:f()
the constexpr specifier only if T::f()
is constexpr?
const can only be used with non-static member functions whereas constexpr can be used with member and non-member functions, even with constructors but with condition that argument and return type must be of literal types.
constexpr functions A constexpr function is one whose return value is computable at compile time when consuming code requires it. Consuming code requires the return value at compile time to initialize a constexpr variable, or to provide a non-type template argument.
The constexpr specifier declares that it is possible to evaluate the value of the function or variable at compile time. Such variables and functions can then be used where only compile time constant expressions are allowed (provided that appropriate function arguments are given).
#define directives create macro substitution, while constexpr variables are special type of variables. They literally have nothing in common beside the fact that before constexpr (or even const ) variables were available, macros were sometimes used when currently constexpr variable can be used.
You just slap a constexpr
on it:
constexpr decltype(auto) f() { return m.f(); }
Yes, it's perfectly still valid even if T::f()
isn't constexpr
; such a function simply can't be used in constant expressions. See [dcl.constexpr]/7.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With