c++ std::enable_if .... else?
What you are looking for is constexpr if. That will let you write the code like
template<typename Obj>
void run(Obj o)
{
if constexpr (std::is_function_v<std::remove_pointer_t<Obj>>)
o();
else
o.print();
}
Live Example
If you don't have access to C++17 but do have C++14, you can at least shorten the code you need to write using a variable template. That would look like
template<typename T>
static constexpr bool is_function_v = std::is_function< typename std::remove_pointer<T>::type >::value;
template<typename Function>
typename std::enable_if< is_function_v<Function>, void>::type
run(Function f)
{
f();
}
template<typename T>
typename std::enable_if< !is_function_v<T>, void>::type
run(T& t)
{
t.print();
}
Live Example
You can use the tag dispatch mechanism if you are limited to using C++11.
namespace detail
{
template<typename Function>
void run(std::true_type, Function& f)
{
f();
}
template<typename Object>
void run(std::false_type, Object& o)
{
o.print();
}
} // namespace detail
template<typename T>
void run(T& t)
{
constexpr bool t_is_a_function =
std::is_function<typename std::remove_pointer<T>::type >::value;
using tag = std::integral_constant<bool, t_is_a_function>;
detail::run(tag{}, t);
}
Working example.