Suppose we have the following “overloaded lambdas template” for two versions (taken from here ):
template <class F1, class F2>
struct overload_set : F1, F2
{
overload_set(F1 x1, F2 x2) : F1(x1), F2(x2) {}
using F1::operator();
using F2::operator();
};
template <class F1, class F2>
overload_set<F1,F2> overload(F1 x1, F2 x2)
{
return overload_set<F1,F2>(x1,x2);
}
which we can use like this:
auto f = overload (
[]( int) { cout << __PRETTY_FUNCTION__ << endl; },
[](char) { cout << __PRETTY_FUNCTION__ << endl; }
);
f('k');
f( 2 );
Now the question is, can we take a general approach to this? I tried with the following (implementation from the same site):
template <class... F>
struct overload_set : F...
{
overload_set(F... f) : F(f)... {}
};
template <class... F>
auto overload(F... f)
{
return overload_set<F...>(f...);
}
but then I get:
main.cpp: In function ‘int main()’:
main.cpp:59:6: error: request for member ‘operator()’ is ambiguous
f(1);
^
main.cpp:51:14: note: candidates are: main()::<lambda(char)>
[](char) { cout << __FILE__ << ":" << __LINE__ << ":" << __PRETTY_FUNCTION__ << endl; });
^
main.cpp:50:13: note: main()::<lambda(int)>
[](int) { cout << __FILE__ << ":" << __LINE__ << ":" << __PRETTY_FUNCTION__ << endl; },
^
main.cpp:60:8: error: request for member ‘operator()’ is ambiguous
f('a');
^
main.cpp:51:14: note: candidates are: main()::<lambda(char)>
[](char) { cout << __FILE__ << ":" << __LINE__ << ":" << __PRETTY_FUNCTION__ << endl; });
^
main.cpp:50:13: note: main()::<lambda(int)>
[](int) { cout << __FILE__ << ":" << __LINE__ << ":" << __PRETTY_FUNCTION__ << endl; },
source
share