Conditionally constexpr member function

2019-05-23 16:56发布

问题:

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?

回答1:

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]/6.