Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally constexpr member function

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?

like image 412
SU3 Avatar asked Jan 07 '17 03:01

SU3


People also ask

Can a member function be 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.

What are constexpr functions?

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.

What does constexpr mean in C++?

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).

Why is constexpr better than #define?

#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.


1 Answers

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.

like image 91
T.C. Avatar answered Sep 23 '22 18:09

T.C.