我不認爲這是在做你想做的任何直接的方式,但這裏是我在我的代碼一些地方使用C++ 11的技術。其基本思想是利用我已經叫call_on_tuple
採取函數參數f
以及進一步的參數的元組的模板功能,展開元組和調用的函數的參數的擴展列表上:
template <typename Fun, typename... Args, unsigned... Is>
typename std::result_of<Fun(Args...)>::type
call_on_tuple(Fun&& f, std::tuple<Args...>&& tup, indices<Is...>)
{ return f(std::get<Is>(tup)...); }
這樣的想法是不是調用
length(arguments());
你會打電話
call_on_tuple(length,arguments());
這假定arguments()
是陳因此它返回一個std::tuple<int,int,int>
(這基本上是你引用的問題的想法)。
現在困難的部分是如何獲得Is...
參數包,這是一組整數0,1,2,...
用於對元組的元素進行編號。
如果你確定你總是會有三個參數,你可以直接使用0,1,2
,但是如果這個野心是爲了使它適用於任何n元函數,我們需要另一個技巧,例如在this post的幾個答案中。
這是一招變換參數的個數,即sizeof...(Args)
成整數0,1,...,sizeof...(Args)
的列表:
我就把這一招和call_on_tuple
在命名空間detail
實現:
namespace detail {
template <unsigned... Is>
struct indices
{ };
template <unsigned N, unsigned... Is>
struct index_maker : index_maker<N-1,N-1,Is...>
{ };
template <unsigned... Is>
struct index_maker<0,Is...>
{ typedef indices<Is...> type; };
template <typename Fun, typename... Args, unsigned... Is>
typename std::enable_if<!std::is_void<typename std::result_of<Fun(Args...)>::type>::value,
typename std::result_of<Fun(Args...)>::type>::type
call_on_tuple(Fun&& f, std::tuple<Args...>&& tup, indices<Is...>)
{ return f(std::get<Is>(tup)...); }
}
現在實際功能call_on_tuple
在全局名稱空間中定義,如下所示:
template <typename Fun, typename... Args>
typename std::enable_if<!std::is_void<typename std::result_of<Fun(Args...)>::type>::value,
typename std::result_of<Fun(Args...)>::type>::type
call_on_tuple(Fun&& f, std::tuple<Args...>&& tup)
{
using std::tuple;
using std::forward;
using detail::index_maker;
return detail::call_on_tuple
(forward<Fun>(f),forward<tuple<Args...>>(tup),typename index_maker<sizeof...(Args)>::type());
}
它基本上調用detail::index_maker
來生成遞增整數的列表,然後用那個調用detail::call_on_tuple
。
其結果是,你可以這樣做:
int length(int x, int y, int z)
{ return x + y + z; }
std::tuple<int,int,int> arguments()
{ return std::tuple<int,int,int> { 1 , 2 , 3 }; }
int main()
{
std::cout << call_on_tuple(length,arguments()) << std::endl;
return 0;
}
是希望足夠接近你需要的東西。
注意。我還添加了一個enable_if
以確保僅用於實際返回值的函數f
。您可以輕鬆地爲返回void
的函數製作另一個實現。
抱歉再次提前關閉您的問題。
PS。您需要添加以下包含語句來測試此:
#include <tuple>
#include <type_traits>
#include <iostream>
每個問題都是重複這些天。 。 。 – Mob
有人downvoted沒有評論,無論如何,你可以使用對象或結構來做到這一點 – vels4j
@jogojapan是的,你是正確的。 – vels4j