4

Suppose we have the following 'overloaded lambdas' template for 2 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 so:

auto f = overload (
    []( int) { cout << __PRETTY_FUNCTION__ << endl; }, 
    [](char) { cout << __PRETTY_FUNCTION__ << endl; }
);

f('k');
f( 2 );

Now the question is whether we can make a generic approach to this? I have tried with the following (implementation from the same website):

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; },
Patryk
  • 22,602
  • 44
  • 128
  • 244
  • Instead of a single `using F::operator()...;` one can recursively bring those operators [with inheritance](http://stackoverflow.com/a/32476942/3953764) – Piotr Skotnicki Oct 25 '15 at 22:10
  • Hmm. That other question is about pretty much the same code, the question about the code is different, but the answer works here too. I suspect it'd be okay to close this as a duplicate. If there's some aspect of your question not adequately answered there, can you edit your question to expand on that? Or is it okay to simply close this question? –  Oct 25 '15 at 22:20
  • @hvd Yup, the answer in linked question works as I wanted. We can close this then. – Patryk Oct 25 '15 at 22:33
  • @PiotrSkotnicki You're right. Let's close this one. – Patryk Oct 25 '15 at 22:34
  • Thanks for the confirmation, done. –  Oct 25 '15 at 22:34
  • @Patryk Note that the linked answer provides linear inheritance. If using a large number of parents (say, more than a few 100), you really want binary tree inheritance, which is trickier. If you don't have a risk of that, then use linear inheritance. – Yakk - Adam Nevraumont Oct 26 '15 at 01:30

0 Answers0