namespace details {
template<template<class...>class, class, class...>
struct can_apply:std::false_type{};
// C++17 has void_t. It is useful. Here is a short implementation:
template<class...>struct voider{using type=void;};
template<class...Ts>using void_t=typename voider<Ts...>::type;
template<template<class...>class Z, class...Ts>
struct can_apply<Z, void_t<Z<Ts...>>, Ts...>:std::true_type{};
}
template<template<class...>class Z, class...Ts>
using can_apply = details::can_apply<Z, void, Ts...>;
template<class A, class B>
using add_result = decltype( std::declval<A>()+std::declval<B>() );
template<class A, class B>
using can_add = can_apply< add_result, A, B >;
now can_add<int, int>
is (inherited from) std::true_type
, while can_add<std::string, void*>
is (inherited from) std::false_type
.
Now, if you are using a non-MSVC c++14 compiler, this works:
template<class A, class B,
std::enable_if_t<can_add<A&,B&>{}, int> =0
>
void only_addable( A a, B b ) {
a+b; // guaranteed to compile, if not link
}
or
template<class A, class B>
std::enable_if_t<can_add<A&,B&>{}, void> // void is return value
only_addable( A a, B b ) {
a+b; // guaranteed to compile, if not link
}
In c++2a the concept proposal will make much of this syntax cleaner.
There is a proposal for is_detected
which works like my can_apply
above.
The declval
part of the add_result
is annoying. Short of concepts, I'm unaware of how to remove it cleanly.