1

I have a function returning a std::pair, which I want to use to call an overloaded member function. I am not aware of any way to unpack a tuple in-place (which I'd prefer), so std::apply is my best bet, I think.

This works with a combination of tuple_cat and forward_as_tuple when the member function is not overloaded, but otherwise, the compiler complains about an unresolved overload. That is understandable, given that std::apply just takes a function pointer, but I'd still like to know whether it can be made to work in a readable way.

Here's some example code:

#include <iostream>
#include <tuple>
#include <utility>

std::pair<int, int> func() { return { 0, 1 }; }

class MyClass {
public:
    int memFun(int);
    int memFun(int, int);
};

int MyClass::memFun(int i){ return 2*i; }
int MyClass::memFun(int a, int b){ return a+b; }

int main(){

    MyClass myClass;

    /* works */
    std::pair pair { func() };
    int number { myClass.memFun( pair.first, pair.second ) };

    /* doesn't work (unresolved overload) */
    int number { std::apply(
        &MyClass::memFun,
        std::tuple_cat( std::forward_as_tuple(myClass), func() )
    ) };

    std::cout << number << "\n";

    return 0;
}

Is there an elegant (=readable) way to do this without a temporary?

I only found this question and so far don't think it fully applies.

RL-S
  • 734
  • 6
  • 21

0 Answers0