【问题标题】:Difference between a template with two parameters and two declarations of templates with one parameter each具有两个参数的模板与每个具有一个参数的两个模板声明之间的区别
【发布时间】:2013-07-08 07:49:01
【问题描述】:

接下来的两个声明有什么区别:

template<class T, class functor>
methodReturnType className::methodName(functor f)

和:

template<class T>
template<class functor>
methodReturnType className::methodName(functor f)

我正在尝试编写一个可以与仿函数 arg 一起使用的方法。 第二个声明允许我避免将整个类声明为 Tfunctor 的模板。我想要一个模板类 className 只有一个参数 T,但在该类中,一个方法有另一个参数 functor,而没有声明整个类作为两个参数的模板。 它有效,但我没有完全理解它。

【问题讨论】:

    标签: c++ templates


    【解决方案1】:

    根据语言规则,第二个变体适合您的情况。

    n3376 14.5.2/1

    会员 在其类模板定义之外定义的类模板的模板应指定为 类模板的模板参数后跟成员模板的模板参数。

    [示例:

    template<class T> struct string {
    template<class T2> int compare(const T2&);
    template<class T2> string(const string<T2>& s) { /∗ ... ∗/ }
    };
    template<class T> template<class T2> int string<T>::compare(const T2& s) {
    }
    

    —结束示例]

    【讨论】:

      【解决方案2】:

      第一个是类的(非模板)成员函数 模板template< typename T, typename functor > class className。第二个是成员函数模板 类模板template &lt;typename T&gt; class className,例如:

      第一:

      template <typename T, class Functor >
      class ClassName
      {
      ReturnType functionName( Functor f );
      };
      

      第二:

      template <typename T>
      class ClassName
      {
      template <typename Functor>
      ReturnType functionName( Functor f );
      };
      

      你说你没有完全理解它,但你似乎 掌握了要点:在第二种情况下,类 模板只有一个参数,但即使在实例化之后 (T 类型的定义),成员函数保持不变 一个模板,可以在许多不同的类型上实例化。 并且由于它是一个函数模板,模板参数 扣除适用,因此您不必指定类型;这 当你调用 功能。

      【讨论】:

        猜你喜欢
        • 2014-03-31
        • 2016-06-30
        • 1970-01-01
        • 2014-04-21
        • 2020-10-01
        • 2019-04-20
        • 1970-01-01
        • 2011-04-21
        • 1970-01-01
        相关资源
        最近更新 更多