[英]How to get a removed-reference tuple type without using an instance in C++
我寫了一個測試框架來測試 function output(見下面的代碼)。
template <class FuncTy, class... IndexType>
typename std::enable_if<std::tuple_size<typename function_helper<FuncTy>::arguments>::value == sizeof...(IndexType)
and std::is_same_v<typename function_helper<FuncTy>::return_type, AnswerTy>
and not is_member_function_pointer_v<FuncTy>, void>::type
test(FuncTy func, IndexType... arg_indexes) {
using function_args_tuple = typename function_helper<FuncTy>::arguments;
using function_return_type = typename function_helper<FuncTy>::return_type;
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
function_args_tuple params; /// error is here
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
/// .....
}
它適用於在 arguments 中沒有引用的函數。
例如:
int f(int x, vector<int> y);
(即,參數列表中沒有引用), params
的類型是std::tuple<int, vector<int>>
,所以params
可以用上面的代碼正常實例化,int f(int& x, vector<int>& y);
這樣的函數 (即參數列表中的一個或多個引用), params
的類型變為std::tuple<int&, vector<int>&>
,無法用上面的代碼實例化。 元組params
的類型受 function 的參數列表的影響(用另一個函數完成),元組的類型未定義,所以我不能這樣做,因為兩個鏈接中的兩個解決方案都使用make_tuple
顯式和實例化元組 object。
所以我的問題是如何在不實例化元組的情況下刪除引用。 (例如,將tuple<int&, vector<int>&>
轉換為tuple<int, vector<int>>
)。
或者,如果有一些方法可以在元組的模板參數列表中使用引用來實例化元組,而無需硬編碼make_tuple
調用。
您可以通過模板部分特化獲取tuple
的元素類型,並將std::decay
應用於這些類型以刪除引用,就像這樣
#include <type_traits>
#include <tuple>
template<class Tuple>
struct decay_args_tuple;
template<class... Args>
struct decay_args_tuple<std::tuple<Args...>> {
using type = std::tuple<std::decay_t<Args>...>;
};
然后你可以通過 helper class 得到一個衰減參數類型的tuple
decay_args_tuple<decltype(function_args_tuple)>::type params;
請注意,參數類型仍然需要是默認可構造的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.