我有一个函数特征结构,它使用 std::tuple_element
提供函数参数的类型:
#include <iostream>
#include <tuple>
#include <typeinfo>
template <typename T>
struct function_traits;
template <typename T_Ret, typename ...T_Args>
struct function_traits<T_Ret(T_Args...)> {
// Number of arguments.
enum { arity = sizeof...(T_Args) };
// Argument types.
template <size_t i>
struct args {
using type
= typename std::tuple_element<i, std::tuple<T_Args...>>::type;
};
};
int main() {
using Arg0 = function_traits<int(float)>::args<0>::type;
//using Arg1 = function_traits<int(float)>::args<1>::type; // Error, should be void.
std::cout << typeid(Arg0).name() << std::endl;
//std::cout << typeid(Arg1).name() << std::endl;
}
如果索引i
超出范围(>= arity
),这会产生编译时错误。相反,我想要 args<i>::type
成为void
对于任何 i
超出范围。
虽然我可以专攻args
具体i
,例如 i == arity
,我怎么能去专攻args
对于所有 i >= arity
?
最佳答案
使用 std::conditional
和额外的间接寻址:
struct void_type { using type = void; };
template <typename T_Ret, typename ...T_Args>
struct function_traits<T_Ret(T_Args...)> {
// Number of arguments.
enum { arity = sizeof...(T_Args) };
// Argument types.
template <size_t i>
struct args {
using type
= typename std::conditional<(i < sizeof...(T_Args)),
std::tuple_element<i, std::tuple<T_Args...>>,
void_type>::type::type;
};
};
关于c++ - 如果索引超出范围,如何从 std::tuple_element 返回 void?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39406519/