Trailing return type, declval and reference qualifiers: can they work together?

Consider the following example:

#include <utility>

struct A { void f() {} };
struct B { void f() & {} };
struct C { void f() && {} };

template<typename T>
auto f() -> decltype(std::declval<T>().f())
{}

int main() {
    f<A>();
    // f<B>(); // (*)
    f<C>();
}

When called with B(string (*)), the code is no longer compiled to std::declvalconvert Tto the rvalue reference type in the specific case.
If we change it a little, we get the inverse problem:

// ...

template<typename T>
auto f() -> decltype(std::declval<T&>().f())
{}

// ...

int main() {
    f<A>();
    f<B>();
    // f<C>(); // (*)
}

Now the string in (*)does not work for std::declvalconverting the type to a reference type lvalue in a specific case.

Is there a way to define an expression that takes a type Tif it has a member function f, no matter what its reference qualifier is?


< > , , - . , .
, , , . >

+4
2

, true, declval<T>().f(declval<Args>()...) . U& U&&, lvalue rvalue T.

namespace detail{
  template<class...>struct voider{using type=void;};
  template<class... Ts>using void_t=typename voider<Ts...>::type;

  template<template<class...> class, class=void, class...>
  struct can_apply : false_type { };

  template<template<class...> class L, class... Args>
  struct can_apply<L, void_t<L<Args...>>, Args...> : true_type {};

  template<class T>
  using rvalue = decltype(declval<T>().f());
  template<class T>
  using lvalue = decltype(declval<T&>().f());

  template<class T>
  using can_apply_f
    = integral_constant<bool, detail::can_apply<rvalue, void_t<>, T>{} ||
                              detail::can_apply<lvalue, void_t<>, T>{}>;
}

template<class T>
enable_if_t<detail::can_apply_f<T>{}>
f();

++ 17 :

namespace detail{
  auto apply=[](auto&&g,auto&&...xs)->decltype(decltype(g)(g).f(decltype(xs)(xs)...),void()){};

  template<class T>
  using ApplyF = decltype(apply)(T);

  template<class T>
  using can_apply_f = std::disjunction<std::is_callable<ApplyF<T&>>, std::is_callable<ApplyF<T&&>>>;
}
+2

Boost.Hana overload_linearly :

template<typename T>
using lval_of = add_lvalue_reference_t<decay_t<T>>;

auto call_f = hana::overload_linearly(
    [](auto&& t) -> decltype(move(t).f()){},
    [](auto&& t) -> decltype(declval<lval_of<decltype(t)>>().f()){}
);

template<typename T>
auto f() -> decltype(call_f(declval<T>()))
{}

0

Source: https://habr.com/ru/post/1660016/


All Articles