c++ std::enable_if .... else?

c++ std::enable_if .... else?

本文关键字:else if enable std c++      更新时间:2023-10-16
#include <stdio.h>
#include <type_traits>
void print()
{
printf("cheers from print !n");
}
class A 
{
public:
void print()
{
printf("cheers from A !");
}
};

template<typename Function>
typename std::enable_if< std::is_function< 
typename std::remove_pointer<Function>::type >::value,
void >::type 
run(Function f)
{
f();
}

template<typename T>
typename std::enable_if< !std::is_function< 
typename std::remove_pointer<T>::type >::value,
void >::type 
run(T& t)
{
t.print();
}

int main()
{
run(print);
A a;
run(a);
return 0;
}

上面的代码按预期编译和打印:

来自印刷品的欢呼! 来自A的欢呼!

我想表达的是:"如果模板是函数,那么应用这个函数,否则......"。或者另一种表述:函数模板有一个函数版本,非函数模板有一个默认版本。

因此,这部分似乎有些多余,可以用"else"条件"替换":

template<typename T>
typename std::enable_if< !std::is_function< 
typename std::remove_pointer<T>::type >::value,
void >::type 
run(T& t)

这会存在吗?

你要找的是 constexpr if。 这将让你编写代码,如

template<typename Obj>
void run(Obj o)
{
if constexpr (std::is_function_v<std::remove_pointer_t<Obj>>)
o();
else
o.print();
}

现场示例

如果您无权访问 C++17,但有 C++14,则至少可以使用变量模板缩短需要编写的代码。 那看起来像

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();
}

现场示例

如果您仅限于使用 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);
}

工作示例。