在大多數通用術語中,我的問題如下:在編譯時定義一系列異構函數指針(可能具有不同的arity),以後需要用任意方式迭代和調用在運行時訂購。迭代和調用元組內的異構函數
將自己約束到C++,最適合的容器,迭代和調用機制是什麼?
這個問題是由現實世界的情況所驅動的,我後來發現了一個更簡單的解決方案,它不涉及元組,而是更專門化的本質。
本來我試圖做這樣的事情:
//type variables Y... have to be convertible to parameters of every function from the tuple std::tuple<T...> in order for this to compile
template<size_t n, typename... T, typename... Y>
void callFunNth(std::tuple<T...> &tpl, size_t i, Y... args) {
if (i == n)
std::get<n>(tpl)(args...);
else
callFunNth<(n < sizeof...(T)-1? n+1 : 0)>(tpl, i, args...);
}
template<typename... T, typename... Y>
void callFun(std::tuple<T...> &tpl, size_t i, Y... args) {
callFunNth<0>(tpl,i, args...);
}
int main()
{
using T1 = int;
namespace mpi = boost::mpi;
//Several instantiations of boost::mpi::reduce algorithm I am interested in
auto algs = make_tuple(boost::bind((void (*)(const mpi::communicator&, const T1*, T1, T1*, std::plus<T1>, int))mpi::reduce<T1, std::plus<T1>>, _1, _2, _3, _4, std::plus<T1>(), _5),
boost::bind((void (*)(const mpi::communicator&, const T1*, T1, T1*, mpi::minimum<T1>, int))mpi::reduce<T1, mpi::minimum<T1>>, _1, _2, _3, _4, mpi::minimum<T1>(), _5),
boost::bind((void (*)(const mpi::communicator&, const T1*, T1, T1*, std::minus<T1>, int))mpi::reduce<T1, std::minus<T1>>, _1, _2, _3, _4, std::minus<T1>(), _5)
);
//Iterate through the tuple and call each algorithm
for(size_t i=0; i < std::tuple_size<decltype(algs)>::value;i++)
callFun(algs, i, /*actual arguments to each algorithm*/);
}
這種方法的問題在於,對於callFunNth在所有提供的參數編譯必須類型轉換爲內部的所有的函數的參數提供的元組嚴重限制了所述函數的異構性,迫使用戶使用std :: bind或boost :: bind來解決此問題。
當類型是相互轉換一個可以寫出如下:
template <typename T, typename U>
void fja(T x, U y) {
std::cout << x << std::endl;
}
auto funs = std::make_tuple(fja<int,std::string>, fja<double,std::string>, fja<char,std::string>);
callFun(funs, 2, 'a', "Char");
callFun(funs, 1, 2.45, "Decimal");
callFun(funs, 0, 1, "Integer");
和具有「一個」,「2.45」和送出分別到stdout
你想遍歷元組(這將意味着元組內相當於參數的所有功能),或做你想基於一個運行時變量獲得一個特定的函數,並用特定的參數調用它? – Xeo 2012-07-16 14:44:06
我不認爲這是可能調用'callFun(玩意兒,我,2.45,「十進制」);',因爲編譯器不知道的是,元組的「I」個元素可以接受雙,其中'我'直到運行時才知道。 – kennytm 2012-07-16 14:59:37
@Xeo這是 – PetarMarendic 2012-07-16 15:08:16