#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;
}

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



我想表达的是:“如果模板是函数,则应用此函数,否则...”。或用另一种表述:具有功能模板的功能版本和非功能模板的默认版本。

因此,这部分似乎有点多余,可以用“其他”条件“替换”:
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();
}

Live Example

如果您没有访问C++ 17的权限,但是拥有C++ 14,则至少可以缩短使用variable template编写的代码。看起来像
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

09-09 23:53