Да предположим, че имаме следния шаблон „претоварени ламбда“ за 2 версии (взет от тук):
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);
}
които можем да използваме така:
auto f = overload (
[]( int) { cout << __PRETTY_FUNCTION__ << endl; },
[](char) { cout << __PRETTY_FUNCTION__ << endl; }
);
f('k');
f( 2 );
Сега въпросът е дали можем да направим общ подход към това? Опитах със следното (имплементация от същия уебсайт):
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...);
}
но тогава получавам:
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; },
using F::operator()...;
може рекурсивно да се приведат тези оператори с наследяване - person Piotr Skotnicki   schedule 26.10.2015