gpt4 book ai didi

c++ - 函数和仿函数作为模板函数的参数

转载 作者:太空狗 更新时间:2023-10-29 23:52:08 27 4
gpt4 key购买 nike

我正在寻找一种将函数指针、仿函数或 lambda 传递给模板函数 g 的方法,该函数使用传递函数的参数类型,例如:

template<class T1, class T2, class T3>
struct wrapper_t {
boost::function<void(T1,T2,T3)> f;
wrapper_t( boost::function<void(T1,T2,T3)> f ) : f(f) {}
void operator( std::vector<T1> &a, std::vector<T2> &b, T3 c ) {
assert(a.size() == b.size());
for(size_t i = 0 ; i != a.size() ; i++) f(a[i], b[i], c);
}
};
template<class T1, class T2, class T3>
wrapper_t<T1,T2,T3> make_wrapper( boost::function<void(T1,T2,T3)> f ) {
return wrapper_t<T1,T2,T3>( f );
}

void f(int, double, char) {};
wrapper_t<int, double, char> w0(f); // need to repeat types

auto w1 = make_wrapper(f); // more comfortable

std::vector<int> a{{1, 2, 3}};
std::vector<double> b{{1.0, 2.0, 3.0}};
w0( a, b, 'c' );
w1( a, b, 'c' );

make_wrapper 函数仅用于从参数中提取类型,一些语法糖可以避免输入两次。


我的问题的一个最小例子是这个函数:

template<class T>
void g1( const boost::function<void(T)> & ) {}

使用这些作为输入

void f1(int) {}
struct f2_t { void operator()(int) {} };

它无法推断 T=int

f2_t f2;
g1( f1 ); // mismatched types ‘const std::function<void(T)>’ and ‘void(int)’
g1( f2 ); // ‘f2_t’ is not derived from ‘const std::function<void(T)>’
g1( [](int){} ); // ‘::<lambda(int)>’ is not derived from ‘…
g1<int>( f1 ); // ok
g1<int>( f2 ); // ok
g1<int>( [](int){} ); // ok

但是 T=int 可以从普通函数指针推断出来,但这不适用于仿函数或 lambda:

template<class T>
void g2( void (*)(T) ) {}

g2( f1 ); // ok
g2( f2 ); // mismatched types …
g2<int>( f2 ); // ok
g2( [](int){} ); // mismatched types …
g2<int>( [](int){} ); // ok

有没有一种方法可以推断 T 不仅适用于普通函数指针,还适用于仿函数和 lambda?

还是一定要这样?

template<class F>
void g( F ) { typedef first_argument_of<F>::type T; }

(在我的真实代码中,我需要用这种方式解构一个有四个参数的函数,但是 std::function::...argument_type 只存在一个或两个参数;boost::function 有 argN_type,但我不认为我可以使用它,因为 F 并不总是 function 这是我的问题,见上文等)

最佳答案

由于种种原因,没有办法如愿以偿。但这里有一个应该可以很清楚地说明问题:

struct function_object
{
template<typename ...T>
void operator ()(T&&... v){}
};

f( function_object{} );

传递给 f 的函数对象的参数类型是什么?没有任何一个,它可以用任何种类和数量的参数调用。

关于c++ - 函数和仿函数作为模板函数的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17181437/

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