我正在努力理解 this code我找到了some more SO content关于这个话题。
以紧凑的形式:
#include <tuple>
namespace sqlite {
namespace utility {
template<typename> struct function_traits;
template <typename Function>
struct function_traits : public function_traits<
decltype(&Function::operator())
> { };
template <
typename ClassType,
typename ReturnType,
typename... Arguments
>
struct function_traits<
ReturnType(ClassType::*)(Arguments...) const
> {
typedef ReturnType result_type;
template <std::size_t Index>
using argument = typename std::tuple_element<
Index,
std::tuple<Arguments...>
>::type;
static const std::size_t arity = sizeof...(Arguments);
};
}
}
这让我了解了该语言的指向成员函数的特性,此时我很清楚如何使用函数特征(这很简单,我不仅可以提取返回类型,还可以提取参数的元数甚至类型),但我一直无法理解为什么这是有效的,或者实际上为什么它可能有效...... .
最佳答案
让我们逐个分解所有内容。
template<typename> struct function_traits;
这是主要的模板声明,声明一个带有单个模板参数的模板类。
template <typename Function>
struct function_traits : public function_traits<
decltype(&Function::operator())
> { };
这本质上是一个转发特征,允许仿函数(具有 operator()
的对象)与这个特征类一起使用。它是从 operator()
的特征继承的主模板的定义。 .当不匹配后面定义的特化时,将选择此版本。
template <
typename ClassType,
typename ReturnType,
typename... Arguments
>
struct function_traits<
ReturnType(ClassType::*)(Arguments...) const
>
这开始了 function_traits
的偏特化定义。用于指向成员函数的指针。当您将成员函数指针类型作为模板参数传递给 function_traits
时, 将选择该专业。返回类型、类类型和参数类型将被推导为模板参数。
typedef ReturnType result_type;
这是一个简单的 typedef
别名推导出ReturnType
模板参数为 result_type
.
template <std::size_t Index>
using argument = typename std::tuple_element<
Index,
std::tuple<Arguments...>
>::type;
这就是所谓的别名模板。当您提供诸如 function_traits<myFunc>::template argument<2>
之类的索引时, 它会折叠成 typename std::tuple_element<2, std::tuple<Arguments...>>::type
.这样做的目的是提取索引 Index
处的参数类型.作者没有写出所有模板元编程代码来手动执行此操作,而是选择使用 std::tuple
中的现有代码。 . std::tuple_element
提取元组的第 n 个元素的类型。
static const std::size_t arity = sizeof...(Arguments);
sizeof...
用于获取可变模板参数包的大小,因此此行将函数的参数数量存储在静态整数成员 arity
中。 .
关于c++ - 了解功能特征模板的工作原理。特别是,指向成员函数的指针是怎么处理的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34283919/