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?

T.C.
  • 133,968
  • 17
  • 288
  • 421
SU3
  • 5,064
  • 3
  • 35
  • 66

1 Answers1

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.

HTNW
  • 27,182
  • 1
  • 32
  • 60
T.C.
  • 133,968
  • 17
  • 288
  • 421