尝试扩展此处找到的示例:https : //stackoverflow.com/a/17974752
基本上,我想从自动传递的函数中推断出参数的数量(这显然对于重载函数不起作用)。我希望这也可以与函子和lambda一起使用。
无法编译对以下参数的调用call_helper
:错误:解析模板参数中的错误
我似乎无法弄清楚如何传递将参数数量作为模板参数返回的constexpr。
这是我到目前为止所拥有的:
#include <vector>
template <typename R, typename ... T>
constexpr std::size_t get_args_count( R(*f)(T ...))
{
return sizeof...(T);
}
template< std::size_t... Ns >
struct indices {
typedef indices< Ns..., sizeof...( Ns ) > next;
};
template< std::size_t N >
struct make_indices {
typedef typename make_indices< N - 1 >::type::next type;
};
template<>
struct make_indices< 0 > {
typedef indices<> type;
};
void abc(int) {}
void abc2(int, int) {}
// helper function because we need a way
// to deduce indices pack
template<typename Func, size_t... Is>
void call_helper2(Func f, const std::vector<int>& args, indices<Is...>)
{
f( args[Is]... ); // expand the indices pack
}
template<typename Func, size_t N>
void call_helper(Func f, const std::vector<int>& args)
{
call_helper2(f, args, typename make_indices<N>::type());
}
template<typename Func>
void call(Func f, const std::vector<int>& args)
{
if (args.size() < get_args_count(f)) throw 42;
call_helper<get_args_count(decltype(f))>(f, args); // error: parse error in template argument list
}
int main()
{
struct F
{
void operator()(int, int, int, int) {}
};
std::vector<int> v(4);
call(&abc2, v);
call(&abc, v);
call([&](int, int, int) { (void)v.empty(); }, v);
call(F(), v);
}
我想念什么或做错什么?任何帮助表示赞赏。
编辑:添加了functor和lambda用例
有两个错误:
call_helper<get_args_count(decltype(f))>(f, args)
,get_args_count(decltype(f))
毫无意义,因为get_args_count
它需要一个函数指针而不是一个类型(显然);您需要尽快提取参数的数量,然后参数f
才能变为可在constexpr
上下文中使用的表达式以外的其他参数。
#include <vector>
template< std::size_t... Ns >
struct indices {
typedef indices< Ns..., sizeof...( Ns ) > next;
};
template< std::size_t N >
struct make_indices {
typedef typename make_indices< N - 1 >::type::next type;
};
template<>
struct make_indices< 0 > {
typedef indices<> type;
};
void abc(int) {}
void abc2(int, int) {}
// helper function because we need a way
// to deduce indices pack
template<typename Func, size_t... Is>
void call_helper2(Func f, const std::vector<int>& args, indices<Is...>)
{
f( args[Is]... ); // expand the indices pack
}
template<typename Func, size_t N>
void call_helper(Func f, const std::vector<int>& args)
{
call_helper2(f, args, typename make_indices<N>::type());
}
template<class R, class ... T>
void call(R(*f)(T ...), const std::vector<int>& args)
{
if (args.size() < sizeof...(T)) throw 42;
call_helper<
decltype(f), sizeof...(T)
>(f, args);
}
int main()
{
std::vector<int> v(2);
call(&abc2, v);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句