【发布时间】:2020-02-17 20:14:37
【问题描述】:
#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 的欢呼!
我想表达的是:“如果模板是函数,则应用此函数,否则......”。或者换一种说法:有一个函数模板的函数版本,以及一个非函数模板的默认版本。
所以,这部分似乎有些多余,可以用“其他”条件“替换”:
template<typename T>
typename std::enable_if< !std::is_function<
typename std::remove_pointer<T>::type >::value,
void >::type
run(T& t)
这会存在吗?
【问题讨论】:
-
否,但您可以使用
using语句简化表达式以减少冗长。 -
@sturcotte06 不明白你的意思 --;
-
正如您评论并要求“过时”的 C++11:如果您限制使用较旧的 C++ 标准,您也应该使用 C++11 标记来标记您的问题。
-
@Klaus 当前的答案为 c++17 和以前的版本提供了答案,所以我想它对使用的任何版本都有用
标签: c++ typetraits enable-if