C++ 11:模板编程

Cfo*_*fon 3 c++ template-meta-programming c++11

我有一些问题.下一个代码是什么意思?

template<typename> 
struct function_traits; // (1)

template<typename ClassType,
             typename ReturnType,
             typename... Arguments>
struct function_traits<ReturnType(ClassType::*)(Arguments...) const> { // (2)
        ...
};

template<typename T>
struct function_traits : public function_traits<decltype(&T::operator())> {}; 
// (3) Why here inheritance?
Run Code Online (Sandbox Code Playgroud)

谢谢!

Ric*_*ges 5

你觉得这是一个谜,这是可以理解的.我们大多数人一开始就做.

第一:

template<typename> 
struct function_traits; // (1)
Run Code Online (Sandbox Code Playgroud)

这声明了模板类的一般形式,它有一个模板参数,它是一个类型(类X,struct Y,int,float,std :: string,等等).请注意,目前已声明模板,但不能从中实例化类,因为模板没有特化.甚至不是默认的.

第二:

template<typename ClassType,
             typename ReturnType,
             typename... Arguments>
struct function_traits<ReturnType(ClassType::*)(Arguments...) const> { // (2)
        ...
    using result_type = ReturnType; // capture the template type into a typedef in the class namespace
};
Run Code Online (Sandbox Code Playgroud)

这定义了模板的部分特化,function_traits<typename T>其中T是任何类的任何成员函数指针,它返回任何返回类型并接受任意数量的参数.因为ReturnType已经分配了模板参数,这意味着允许该类的定义将其称为类型,从而推导出result_type成员函数.

但是,在这个阶段,专门化是没有用的,因为调用者需要在调用站点指定完整的函数指针,如下所示:function_traits<&SomeClass::someFunction>处理重载将是棘手的.

现在第三部分进行了一个"接口"专业化,它表示对于任何一个类T,都function_traits<T>应该从中派生出来function_traits<&T::operator()>.

template<typename T>
struct function_traits : public function_traits<decltype(&T::operator())> {}; 
// (3) Why here inheritance?
Run Code Online (Sandbox Code Playgroud)

由于模板扩展中存在这样的特定匹配,因此仅针对具有调用operator(operator())的类型进行扩展.基类从第二个特化提供返回类型,因此该模板能够捕获具有调用操作符的任何类型的返回类型.因为此类派生自捕获返回类型的实际类,result_type所以也是此类范围的一部分.

现在我们可以写:

struct Foo {
    int operator()();
};

using foo_ret = function_traits<Foo>::result_type;
Run Code Online (Sandbox Code Playgroud)

而foo_ret将是int.

仍然困惑?欢迎来到您的前6个月的模板编程.