使用参数向量调用函数

问题描述 投票:1回答:1

我有一个std::vector的参数,我想用它们调用一个函数。有没有办法做到这一点?

特别是函数是mysqlx select函数,参数是我试图查询的列;他们都将是std::string类型。该功能的目的是减少代码库中的重复。

(这似乎是一个非常有用的主题,但我找不到通过搜索得到的答案。如果我错过了它并且已经得到了回答,请指出我的问题并将其作为重复复制,谢谢。)

c++ c++14 dry variadic
1个回答
3
投票

您可以这样做,最多可以编译一次参数。它不漂亮。

using result_type = // whatever
using arg_type = // whatever
using args_type = const std::vector<arg_type> &;
using function_type = std::function<result_type(args_type)>;

template <size_t... Is>
result_type apply_vector_static(args_type args, std::index_sequence<Is...>)
{
    return select(args[Is]...);
}

template<size_t N>
result_type call_apply_vector(args_type args)
{ 
    return apply_vector_static(args, std::make_index_sequence<N>()); 
}

template <size_t... Is>
std::map<size_t, function_type> make_funcs(std::index_sequence<Is...>)
{
    return { { Is, call_apply_vector<Is> }... };
}

result_type apply_vector(args_type args)
{
    // Some maximum limit
    static const auto limit = std::make_index_sequence<50>();
    static const auto funcs = make_funcs(limit);
    return funcs.at(args.size())(args);
}

See it live

© www.soinside.com 2019 - 2024. All rights reserved.