我想实现以下功能:
template<typename Function, typename... Parameters>
inline void foo(
const Function& kernel_function,
bar_t bar
Parameters... parameters)
{
static_assert(/* magic */,
"You can only foo() a function, not values of any other type");
/ * etc. etc. */
}
我需要它只使用函数的标识符或指向函数的指针来调用:没有带有 operator()
或 std::function
s 的 lambad 或方法或类。我应该用什么替换/* magic */
?仅仅使用std::is_function
似乎不起作用。
<type_traits>
我们有std::is_function
,如果你给它传递一个实际的函数并使用lambdas,具有重载operator()
的类和指向函数的指针false
,它会返回true
。我们还有std::is_pointer
和std::remove_pointer
可用于检查和删除函数指针中的指针类型,以使用 std::is_function
测试指针。 使用你的断言看起来像
static_assert(std::is_function<Function>::value ||
(std::is_pointer<Function>::value &&
std::is_function<std::remove_pointer<Function>::type>::value),
"You can only foo() a function, not values of any other type");
基于@DietmarKuhl在重复问题中的回答:
#include <type_traits>
#include <utility>
template<typename Fun>
struct is_function_ptr: std::integral_constant<bool,
std::is_pointer<Fun>::value and
std::is_function<typename std::remove_pointer<Fun>::type>::value> { };
template<typename Function, typename... Parameters>
inline void foo(
const Function& kernel_function,
bar_t bar
Parameters... parameters)
{
static_assert(
std::is_function<Function>::value or is_function_ptr<Function>::value,
"You can only foo() a function, not values of any other type");
/ * etc. etc. */
}
虽然,老实说,我没有进行广泛的测试。