gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 04:20:34 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com