假设我们有以下'重载的lambdas' 2个版本的模板(取自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);
}
我们可以这样使用:
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; },