给定一组函数,例如:
template<class A1>
Void Go(A1 a);
template<class A1, class A2>
Void Go(A1 a1, A2 a2);
template<class A1, class A2, class A3>
Void Go(A1 a1, A2 a2, A3 a3);
是否可以采用某种变体类型的数组并根据其内容触发正确的功能?我的应用程序是我想将一组参数 X 传递给另一个进程,在那里我只能选择传递单个指针。我的想法是发送一个指向 std::vector<boost::any> 的指针,然后根据其内容以某种方式计算出上述哪些方法可以触发。
这涉及我对跨线程事件和通信的实验,因此它可能看起来不必要的深奥!
编辑:好的,例如,这是意图。显然它不会编译(模板解析发生在编译时,但我想确定在运行时调用哪个函数!):
#include <boost\any.hpp>
#include <vector>
#include <iostream>
#include <string>
class A
{
public:
void Go()
{
std::cout << L"(0 params)\n";
}
template
void Go(U0 u0)
{
std::cout << L"1 param " << u0 << L"\n";
}
template
void Go(U0 u0, U1 u1)
{
std::cout << L"2 params " << u0 << L" " << u1 << L"\n";
}
template
void Go(U0 u0, U1 u1, U2 u2)
{
std::cout << L"3 params " << u0 << L" " << u1 << L" " << u2 << L"\n";
}
};
class B
{
public:
void Whatever() {}
};
int main(int argc, wchar_t* argv[])
{
// Create a collection of variants.
std::vector<boost::any> myVariants;
B myB;
myVariants.push_back(123);
myVariants.push_back(std::wstring(L"Test"));
myVariants.push_back(&myB);
// Take a void pointer to them.
void *variants = &myVariants;
// Convert back into an array.
std::vector<boost::any>& myConverted = *(std::vector<boost::any> *)(variants);
// Fire the correct event on A.
A myA;
switch(myConverted.size())
{
case 0:
myA.Go();
break;
case 1:
myA.Go(myConverted[0]);
break;
case 2:
myA.Go(myConverted[0], myConverted[1]);
break;
case 3:
myA.Go(myConverted[0], myConverted[1], myConverted[2]);
break;
default: ;
// throw
}
}