如何获取指向已推断的模板函数的指针?

How could I get a pointer to an already-deduced template function?

本文关键字:指针 函数 取指 何获      更新时间:2023-10-16

我有一个模板函数,我想在自动推断其模板参数的情况下使用它。

它运行良好,但现在我需要它的ptr用于std::bind.

它是这样的:

class A{};
class B{};
class C{};
template<template<typename...> class TContainer, typename TR, typename... TEles>
void func(TContainer<TEles...> container, function<TR(HeadOf<TEles...>::type)> f)
{
TContainer<TR> rst;
for(auto it : container)
{
fill(rst, f(it));
}
return rst;
}
vector<A>      vec_A;  // type : vector<A, allocator<A>>
MyContainer<B> cont_B; // type : MyContainer<B, allovator<B>, Maybe_Sth_Else>  
// auto ptrFoo = func_ptr_of( func(vec_A, transA2B) );
// auto ptrBar = func_ptr_of( func(cont_B, transB2C) );
// auto contB2contC = std::bind(ptrBar, placeholder::_1, transB2C);
// contB2contC(cont_B);

我认为这是不可能的。

但是如果你有一个 C++14 编译器,你可以用可变参数 lambda 做类似的事情。

通过示例

A  a{};
auto fakeBondFunc = [&](auto ... as) { func(a, as...); };
fakeBondFunc(B{});

如果你想修复第一个A参数并强制要求第二个参数是B参数,你也可以在 C++11 中执行此操作(不需要可变参数 lambda(

A  a{};
auto fakeBondFunc = [&](B const & b) { func(a, b); };
fakeBondFunc(B{});
using ptr_t = void(*)(A, B);
ptr_t ptrFoo = func<A, B>;
std::function<void(B)> boundFunc = std::bind(ptrFoo, A{}, std::placeholders::_1);
boundFunc(B{});