我有下面的代碼段,其中我定義struct quick
與模板static
方法random
一些專業:(。我使用來自其他function_traits
SO回答附於底部供參考)如何從參數包中獲取所有參數的類型?
struct quick
{
template <typename T>
static T random();
template <typename F>
static void check(F f)
{
constexpr auto arity = function_traits<F>::arity; // easy :)
std::cout << arity << std::endl;
typedef typename function_traits<F>::template arg<0>::type type0; // easy:)
// how to get all types of all F's parameters?
}
};
template <>
std::string quick::random<std::string>()
{
return std::string("test");
}
template <>
int quick::random<int>()
{
return 1;
}
我想獲得所有類型的F
的參數在check
之內,這樣我就可以用隨機條目生成tuple
(基於我的random
方法專業化)。
像這樣:
auto t0 = std::make_tuple(quick::random<AllTypes>()...); //pseudo code
auto t =
std::make_tuple(quick::random <
function_traits<F>::template arg<std::make_index_sequence<arity>>::type...
>
()...
);
我試過的東西,如:
template<typename F, typename ...TIdxs>
using ArgTypes = typename function_traits<F>::template arg<TIdxs>::type...;
// ...
// inside check
typedef ArgTypes<F, std::make_index_sequence<arity>> types;
但悲慘地失敗了:
main.cpp:80:72: error: expected ‘;’ before ‘...’ token
using ArgTypes = typename function_traits<F>::template arg<TIdxs>::type...;
^
main.cpp: In static member function ‘static void quick::check(F, D)’:
main.cpp:98:15: error: ‘ArgTypes’ does not name a type
typedef ArgTypes<F, std::make_index_sequence<arity>> types;
我用function traits
公用事業從this SO回答。
template <typename T>
struct function_traits : function_traits<decltype(&T::operator())>
{};
// For generic types, directly use the result of the signature of its 'operator()'
template <typename ClassType, typename ReturnType, typename... Args>
struct function_traits<ReturnType(ClassType::*)(Args...) const>
// we specialize for pointers to member function
{
enum { arity = sizeof...(Args) };
// arity is the number of arguments.
typedef ReturnType result_type;
template <size_t i>
struct arg
{
typedef typename std::tuple_element<i, std::tuple<Args...>>::type type;
// the i-th argument is equivalent to the i-th tuple element of a tuple
// composed of those arguments.
};
};
像往常一樣,功能特點onky作品有時。 'auto f = [](auto && x){return 2 * x;}'。關於'TIdxs'的 – Yakk