我可以在lambda中使用可变模板吗
Can I use variadic templates in a lambda?
我能让它工作吗?
假想语法:
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
相关文章:
- 函数向量_指针有不同的原型,我可以构建一个吗
- 我可以使用 g++ 进行三种比较 (<=>) 吗?
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 我可以信任表示整数的浮点或双精度来保持精度吗
- 我可以将调用类的"this"传递给 lambda 函数吗?
- 我可以在这里替换什么,因为我不能在 C# 中使用隐式变量的 lambda 函数?
- 我可以使用 lambda 来简化 for 循环吗?
- 我可以让返回类型自动处理具有相同签名但捕获不同内容的 lambda 吗?
- 为什么我可以在 C++ 的可变 lambda 中捕获未声明的变量
- 我可以在模板参数中声明一个 constexpr lambda 吗?
- 我可以将C 17 Capture lambda ConstexPR转换操作符的结果用作函数指针模板非类型参数吗?
- 为什么我可以在 lambda 中使用 ostream cout,尽管它没有被捕获?
- 我可以将 std::function (C++11 lambda) 与 Boost 一起使用吗?
- 我可以在Visual Studio中的Lambda中定义一个模板化函数
- 我可以定义一个没有auto的C++lambda函数吗
- 我可以在std::函数中使用模板类型T来传递lambda类型的函数C++11吗
- 我可以强制c++ 11的lambda通过引用返回吗?
- 我可以做一个有相同签名的String + lambda表吗?
- 我可以在lambda中使用可变模板吗
- 我可以有主窗口过程作为一个lambda在WinMain