我可以在lambda中使用可变模板吗

Can I use variadic templates in a lambda?

本文关键字:lambda 我可以      更新时间:2023-10-16

我能让它工作吗?

假想语法:

auto foo = [] () { };
template <class T, typename ... Args>
auto foo =
[&] (T && V, Args && ... args) {
    do_something(V);
    foo(std::forward<Args>(args)...);
};

正如评论中所提到的,您不能真正做到这一点,因为lambda不够强大。

当允许[](auto val){}语法时,这将容易得多。

我使用以下内容对元组进行基本调用

template<typename Tuple_t, typename Func_t, std::size_t k_index = 0>
//Only come here if the passed in index is less than sie of tuple
    typename std::enable_if<k_index <  tuple_size<Tuple_t>::value>::type 
    call_over_tuple(Tuple_t& irk_tuple, Func_t i_func){
    i_func(get<k_index>(irk_tuple));
    call_over_tuple<Tuple_t, Func_t, k_index + 1>(irk_tuple, i_func);
}
template<typename Tuple_t, typename Func_t, std::size_t k_index>
typename std::enable_if < k_index >=  tuple_size<Tuple_t>::value>::type
    call_over_tuple(Tuple_t& irk_tuple, Func_t i_func){
             //do nothing
}

将其扩展为仅随机参数即可。

template<typename Func_t, typename ...Args>
void call_over_vals(Func_t i_func, Args&&... i_args){
    auto arg_tuple = make_tuple(forward<Args>(i_args)...);
    call_over_tuple<decltype(arg_tuple), Func_t>(arg_tuple, i_func);
}

为了让函数重载或模板,你需要创建一个主叫类来完成你的出价。

template<typename T>
void do_something(const T& irk_val){
    cout << irk_val;
}
class caller_class{
public:
    template<typename T>
    void operator()(const T& i_val){
        do_something(i_val);
    }
private:
};
void print_integer(int i_val){
    cout << i_val;
}
int main(int argv, char** argc){
    call_over_vals(caller_class(), 3, ' ' ,  2, " asdf ", 4, "n");

    //If you know the argument type just pass it in
    call_over_vals(print_integer, 1, 2, 3, 4, 5);
    cout << "n";
    call_over_vals([](int y_val){cout << y_val; }, 1, 2, 3, 4, 5);
}

输出:

3 2 asdf 4
12345
12345