我正在玩一个用C++重载lambdas的技巧.特别:
// For std::function
#include <functional>
// For std::string
#include <string>
// For std::cout
#include <iostream>
template <class... F>
struct overload : F... {
overload(F... f) : F(f)... {}
};
template <class... F>
auto make_overload(F... f) {
return overload<F...>(f...);
}
int main() {
std::function <int(int,int)> f = [](int x,int y) {
return x+y;
};
std::function <double(double,double)> g = [](double x,double y) {
return x+y;
};
std::function <std::string(std::string,std::string)> h = [](std::string x,std::string y) {
return x+y;
};
auto fgh = make_overload(f,g,h); …
Run Code Online (Sandbox Code Playgroud) 我正在研究一种可能被称为"overloaded lambda"的C++ 11习语:
使用可变参数模板重载n个函数似乎对我很有吸引力,但事实证明它不适用于变量捕获:任何[&]
[=]
[y]
[&y]
([this]
如果在成员函数中)等导致编译失败:( error: no match for call to '(overload<main(int, char**)::<lambda(int)>, main(int, char**)::<lambda(char*)> >) (char*&)'
使用我的本地GCC 4.9.1和ideone .com GCC 5.1)
另一方面,固定的2-ary情况没有遇到这个问题.(尝试改变第一#if 0
到#if 1
上ideone.com)
关于这里发生了什么的任何想法?这是编译器错误,还是我偏离了C++ 11/14规范?
#include <iostream>
using namespace std;
#if 0
template <class F1, class F2>
struct overload : F1, F2 {
overload(F1 f1, F2 f2) : F1(f1), F2(f2) { }
using F1::operator();
using F2::operator();
};
template <class F1, class F2>
auto …
Run Code Online (Sandbox Code Playgroud) c++ lambda template-meta-programming variadic-templates c++11