c++ - 指向模板函数的空指针

标签 c++ templates pointers void

假设这不是我管理的模板函数:

template<class T, class U>
U templatefunc(T t){ //(...); }

我可以有一个默认参数是模板函数类型的函数吗

templatefunc<int,double> 

然后如何声明 void 指针,所以我可以这样做:

void _new_func( const void*=&templatefunc<int,double>)

我认为不是,因为你不能有指向函数的 void 指针,它必须是函数指针,对吧?

以前是:

void _new_func(const void* = boost::test_tools::check_is_close) 

但是对于 boost 1.54 是不行的,因为 check_is_close 是模板。

最佳答案

&templatefunc<int,double> 的类型是指向返回 double 的函数的指针并采用一个 int 类型的参数.模板参数不再重要 - templatefunc<int,double>只是(实例化的)函数的名称。所以你可以:

void _new_func(double(*func)(int) = &templatefunc<int,double>)

但是,您似乎想要采用具有不同参数和返回类型的函数。在这种情况下,您可以在不传递任何参数的情况下进行重载:

template <typename T, typename U>
void _new_func(U(*func)(T)) {
}

void _new_func() {
  _new_func(&templatefunc<int,double>);
}

现在您可以调用_new_func()它将传递函数指针 &templatefunc<int,double>到模板化版本。当你想调用_new_func使用不同的实例化 templatefunc ,例如,您可以执行以下操作:

__new_func(&templatefunc<float, double>);

关于c++ - 指向模板函数的空指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15209759/

相关文章:

c++ - 如何对数组 int (*&Test)[10] 进行赋值?

c++ - 从引用参数将对象初始化为空列表

c++ - constexpr 是编译器的 "hint"(如内联)还是 "a binding request"?

C++ 使用命名空间 std,使用 std::xxx 还是仅使用 std::x?

C - 在带有指针的结构的循环中进行 malloc

c - C代码的不合逻辑输出

c++ - C++ 中基类和派生类的作用域

c++ - 模板参数类型

c++ - "Ambiguous template specialization"问题

python - 如何在 Django 模板中访问外键表的数据?