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?
Argument Order MattersThe order or arguments supplied to a function matters.
Most programming languages force you to order your function parameters. Getting them wrong might break your code.
Parameters are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma.
It doesn't matter what order they are given in the parameter so long as the arguments in the call expression match the correct variable. Either way won't matter to the output string. The format arguments are ordered according to how they present.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With