如果索引超出范围,如何从 std::tuple_element 中 return 作废?

How to return void from std::tuple_element if index is out of range?

我有一个函数特征结构,它使用 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;
}

Working example: Ideone

如果索引 i 超出范围 (>= arity),则会出现编译时错误。相反,对于任何超出范围的 i,我希望 args<i>::typevoid

虽然我可以为特定的 i 专门化 args,例如 i == arity,但我如何才能为所有 i >= arity 专门化 args

使用 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;
    };
};

Demo