【发布时间】:2016-09-09 07:52:19
【问题描述】:
我有一个函数特征结构,它使用 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),则会出现编译时错误。相反,对于任何超出范围的i,我希望args<i>::type 成为void。
虽然我可以将args 专门用于特定的i,例如i == arity,但我如何才能将args 专门用于所有i >= arity?
【问题讨论】:
-
你能为我们扩展代码吗?所以我们可以编译这个?就像一个简单的用例等。
-
@Hayt 完成:ideone.com/qM9Jxp
标签: c++ templates c++11 stdtuple