在参数包中获取 return 类型的函数指针并将其保存为与其他参数的连接元组
Getting return type of a function pointer in parameter pack and saving it as concatenated tuple with other args
我想根据传递的参数包定义一个元组类型,该类型将包含所有不是函数的参数,并且代替那些函数只是保存它们的 return 类型。该类型稍后将用于哈希映射中的索引,因此我需要一种方法来获取它
std::result_of 似乎是问题的解决方案,在我的测试代码中,如果只传递函数指针,它就可以工作。但在我的用例中,也可能会传递其他基本类型,即使我添加了 std::conditional check
也会抛出 "error: no type named ‘type’ in ‘class std::result_of’"
template <typename ...Args>
using tuple_cat_t = decltype(std::tuple_cat(std::declval<Args>()...));
template <typename ...Args>
void eval(Args... args) {
using tuple_t = std::tuple<Args...>;
using pattern_t = tuple_cat_t<
typename std::conditional <
std::is_pointer<Args>::value && std::is_function<typename std::remove_pointer<Args>::type>::value,
std::tuple < std::result_of_t<Args&&()> > ,
std::tuple<Args>
>::type...
>;
}
int fn(){ return 5; }
int main(){
eval(fn,fn); //all good, pattern type is std::tuple<int, int>
eval(5,fn); //comilation error
}
您过于急切地评估元功能。 result_of
部分也针对 int
进行评估。
您应该重新排列条件,使您选择的是元函数而不是类型,然后对其求值:
template <typename T> struct identity { using type = T; };
template <typename Arg>
using maybe_eval = typename std::conditional_t<
std::is_pointer<Arg>::value && std::is_function<typename std::remove_pointer<Arg>::type>::value,
std::result_of<Arg&&()>,
identity<Arg>
>::type;
using pattern_t = tuple_cat_t<std::tuple<maybe_eval<Args>>...>;
请注意,我正在使用 两者 conditional_t
和 type
我想根据传递的参数包定义一个元组类型,该类型将包含所有不是函数的参数,并且代替那些函数只是保存它们的 return 类型。该类型稍后将用于哈希映射中的索引,因此我需要一种方法来获取它
std::result_of 似乎是问题的解决方案,在我的测试代码中,如果只传递函数指针,它就可以工作。但在我的用例中,也可能会传递其他基本类型,即使我添加了 std::conditional check
也会抛出 "error: no type named ‘type’ in ‘class std::result_of’"template <typename ...Args>
using tuple_cat_t = decltype(std::tuple_cat(std::declval<Args>()...));
template <typename ...Args>
void eval(Args... args) {
using tuple_t = std::tuple<Args...>;
using pattern_t = tuple_cat_t<
typename std::conditional <
std::is_pointer<Args>::value && std::is_function<typename std::remove_pointer<Args>::type>::value,
std::tuple < std::result_of_t<Args&&()> > ,
std::tuple<Args>
>::type...
>;
}
int fn(){ return 5; }
int main(){
eval(fn,fn); //all good, pattern type is std::tuple<int, int>
eval(5,fn); //comilation error
}
您过于急切地评估元功能。 result_of
部分也针对 int
进行评估。
您应该重新排列条件,使您选择的是元函数而不是类型,然后对其求值:
template <typename T> struct identity { using type = T; };
template <typename Arg>
using maybe_eval = typename std::conditional_t<
std::is_pointer<Arg>::value && std::is_function<typename std::remove_pointer<Arg>::type>::value,
std::result_of<Arg&&()>,
identity<Arg>
>::type;
using pattern_t = tuple_cat_t<std::tuple<maybe_eval<Args>>...>;
请注意,我正在使用 两者 conditional_t
和 type