Conditionally constexpr member function
Asked Answered
A

1

11

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?

Arly answered 7/1, 2017 at 3:50 Comment(0)
T
14

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.

Trapezium answered 7/1, 2017 at 4:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.