【问题标题】:Access template parameter from class object从类对象访问模板参数
【发布时间】:2018-09-17 13:41:42
【问题描述】:

我在 myclass.hpp 中有一个类模板:

template<class T, class P>
class myclass
{
....
};

在我的 main.cc 中,我创建了一个类的对象:

myclass<int, double> mc;
otherfunc<myclass>(mc);

在其他一些头文件header1.hpp中:

template<class MyClass>
void otherfunc(MyClass const &mc)
{
/* Access through 'mc' the underlying template parameters T and P*/
}

如何访问 header1.hpp 中的模板参数 T 和 P?

【问题讨论】:

  • otherfunc&lt;myclass&gt;(mc) 对给定的otherfunc 声明无效。你可以使用otherfunc(mc)(让扣除发生)或otherfunc&lt;myclass&lt;int, double&gt;&gt;(mc)

标签: c++ templates class-template


【解决方案1】:

如何访问 header1.hpp 中的模板参数 T 和 P?

在您的类myclass 中提供public 类型定义:

template<class T, class P>
class myclass
{
public:
     typedef T T_type;
     typedef P P_type;
....
};

因此您可以访问这些类型

typename myclass::T_Type x;
typename myclass::P_Type y;

其他地方。

【讨论】:

    【解决方案2】:

    例子:

    template<class T, class P>
    void otherfunc(myclass<T, P> const &mc)
    {}
    

    或者:

    template<class T, class P>
    class myclass
    {
        using ParamT = T;
        using ParamP = P;
    };
    
    template<class MyClass>
    void otherfunc(MyClass const &mc)
    {
        using ParamT = typename MyClass::ParamT;
        using ParamP = typename MyClass::ParamP;
    }
    

    【讨论】:

      【解决方案3】:

      #1

      一种方法是在myclass 中键入def。

      template<class T, class P>
      class myclass
      {
      public:
          typedef T typeT;
          typedef P typeP;
      };
      

      然后像这样称呼他们

      template<class MyClass>
      void otherfunc(MyClass const &mc)
      {
          typename MyClass::typeT myMember;
      }
      

      #2

      另一种方法是使用decltype。您可能实际上不需要使用模板参数,但打算使用与成员相同的类型或 myclass 成员的返回值。因此,像这样:

      template<class T, class P>
      struct myclass
      {
        T memberT;
        P memberP;
      };
      
      template<class MyClass>
      void otherfunc(MyClass const &mc)
      {
        using T = decltype(MyClass::memberT);
        using P = decltype(MyClass::memberP);
        T var1;
        P var2;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-13
        • 2018-11-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多