【问题标题】:Template class specialization function call. C++模板类特化函数调用。 C++
【发布时间】:2015-04-30 11:09:00
【问题描述】:

考虑一下这段代码。

template<class T>
class A
{
    public:
      void f(){..}
      void h(){..}
};


template<>
class A<int>
{
    public:
      void f(){// something different..}
      //void h(){..}
};

int main()
{
    A<int> obj;
    obj.h(); // I want to call A<T>::h(), but compiler erred that there is no h function in A<int>
}

有没有办法打这个电话?或者一些解决方法?

【问题讨论】:

  • 编译器是正确的。您可以将 h 函数放在别处,例如一个基类。
  • @Eduard Rostomyan 如果它不存在,你将如何称呼它?
  • @VladfromMoscow,我想调用 commot A :: h(),我不知道怎么做,如果我知道我宁愿问这个问题。
  • @Eduard Rostomyan 按照设计,专业化 A 没有该功能。所以要么你应该重新设计模板,要么不调用函数。

标签: c++ templates template-specialization specialization


【解决方案1】:

A&lt;T&gt; 是一个类模板,它基于任何类型名称T 引入了一系列类AA&lt;int&gt;A&lt;T&gt; 的显式特化——它取代了泛型类定义。和写的没什么区别:

class Aint {
public:
    void f(); 
};

这个特化只有一个成员函数 - f。所以当你尝试这样做时:

A<int> obj;
obj.h();

因为A&lt;int&gt; 没有名为h 的成员函数,所以无法编译。尽管都被命名为AA&lt;int&gt;A&lt;T&gt; 是不相关的 - 一个不是另一个的基类,一般 A&lt;T&gt; - A&lt;int&gt; 中存在什么函数和成员并不重要专业没有它们。

如果h 很常见,您可以将它移到基类中:

struct ABase { // or alternatively ABase<T>
    void h();
}

template <typename T>
class A : ABase {
    void f();
};


template <>
class A<int> : ABase {
    void f();
};

这样A 的所有实例化都会有一个h()。也就是说,直到有人继续添加:

template <>
class A<char> // no inheritance
{
    // no h()
};

【讨论】:

    【解决方案2】:

    根据你在专业领域中改变了多少东西,你最好只专注于 fA&lt;int&gt; 而不是专注于整个课程:

    template<class T>
    class A
    {
        public:
          void f(){cout << "standard";}
          void h(){cout << "standard";}
    };
    
    template<>
    void A<int>::f() {cout << "specialized";}
    
    int main()
    {
        A<bool>{}.f(); //outputs standard
        A<int> obj;
        obj.f();       //outputs specialized
        obj.h();       //outputs standard
    }
    

    如果您的专业化比这更复杂,您可以将常见行为分解到基类中并从中派生A

    【讨论】:

      【解决方案3】:

      此代码适用于我:

      template<class T>
      class BaseA {
      public:
        void f(){...}
        void h(){...}
      };
      
      template<class T>
      class A : public BaseA<T>
      {
      };
      
      
      template<>
      class A<int> : public BaseA<int>
      {
          public:
            void f(){...}
            //void h(){..}
      };
      
      int main()
      {
          A<int> obj;
          obj.h(); // I want to call A<T>::h(), but compiler erred that there is no h function in A<int>
      }
      

      它声明了一个被两者继承的基类。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-06-27
        • 2013-09-24
        • 1970-01-01
        • 2011-09-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多