简体   繁体   中英

How to reorder function parameters?

Look at the pseudo-c++ code below:

typedef *** SomeType1;
typedef *** SomeType2;
typedef *** SomeType3;

void BFunc(SomeType1& st1, SomeType2& st2, SomeType3& st3)
{
    /*some work*/;
}

template <typename T1, typename T2, typename T3>
void AFunc(T1& p1, T2& p2, T3& p3)
{
    BFunc(???);
}

There are two functions with parameters. The parameters count larger than three, but for simplicity for example let it would be three.

The Afunc - it is the templated function that have the same parameters count as the BFunc plus the parameters have the same types as the BFunc parameters. But (!) the sequence on the parameters of BFunc can (or cannot) be different. For example:

BFunc(int, double, char)

AFunc<double, int, char>
AFunc<int, double, char>
AFunc<char, double, int>
AFunc<char, int, double>
...

So how to reorder parameters inside AFunc for calling BFunc with correct parameters sequence?

You can use std::get to fetch a value by its type from a tuple and std::tie to bundle your arguments into a tuple of references.

Obviously, this only works if your argument types are unique.

Make sure std::get uses a reference type to avoid unnecessary copies.

#include <tuple>

// arbitrary argument types
struct SomeType1{};
struct SomeType2{};
struct SomeType3{};

void BFunc(SomeType1& st1, SomeType2& st2, SomeType3& st3)
{
    /*some work*/;
}

template <typename T1, typename T2, typename T3>
void AFunc(T1& p1, T2& p2, T3& p3)
{
    // Make a tuple of references to all the arguments
    auto tuple = std::tie(p1, p2, p3);

    // Find the right arguments in the tuple
    BFunc(
        std::get<SomeType1&>(tuple), 
        std::get<SomeType2&>(tuple), 
        std::get<SomeType3&>(tuple));
}

int main()
{
    SomeType1 t1;
    SomeType2 t2;
    SomeType3 t3;

    AFunc(t1,t2,t3);
    AFunc(t1,t3,t2);
    AFunc(t2,t1,t3);
    AFunc(t2,t3,t1);
    AFunc(t3,t1,t2);
    AFunc(t3,t2,t1);
}

Try it here: https://godbolt.org/z/7Gdc5qozW

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM