如何为模板类的专用版本添加成员变量?

时间:2019-04-09 05:36:32

标签: c++ templates template-specialization specialization member-variables

我有一个模板类,并且对于所有类型的模板参数,至少有95%的代码是相同的,除非应为一个专门化添加成员变量和函数。

我要获取的示例如下:

template <typename T>
class AClass {
private:
   T  payLoad;

public:
   AClass( const T& crp_payload ) : payLoad( crp_payload ) {};

   void showMe() {
      cout << "Common showMe:" << payLoad << endl;
   };

   /*
    * A lot of functions same for all specializations go here.
    * I absolutely don't want to implement respectively them for
    * every specializations!
    */

// specializing for int ----------------------------
   // dedicated function
   template <int>
   void showPayload() {
      cout << "AClass<int>::showPayload:" << payLoad << endl;
   };
   // dedicated variable, but following code can not be compiled!
   template <int>
   int   otherPayload;
};

int main() {
   AClass<int> iac( 123 );
   iac.showMe();
   iac.showPayload();//can not pass the compiling!

   AClass<float> fac(456);
   fac.showMe();
   return 0;
};

我的问题:

  1. 如何仅添加“ otherPayload”变量而不重新编码整个 AClass<int>
  2. 如何调用showPayload() sinc我收到错误信息     如上在main()中进行操作。
  3. 没有办法只能专门“修改/补充”一些 成员没有完全重新实现吗?

2 个答案:

答案 0 :(得分:3)

一种可能的方法是良好的旧继承:

template<class T> struct Extra {};

template<> struct Extra<int> {
    int extraPayload;
    void showPayload();
};

template<class T> class Class: public Extra<T> {
    void showMe();
};

template<> void Class<int>::showMe() { showPayload(); }

所有特定于专业化的部分都被提取到一个单独的类中,并且根据需要对通用方法进行了专门化。

答案 1 :(得分:3)

我认为您可以简单地对模板类进行常规的专业化处理:

#include <iostream>
#include <iomanip>

template <typename T>
class BaseClass 
{
protected:
    T  payLoad;

public:
    BaseClass(const T& crp_payload)
        : payLoad( crp_payload )
    { }

    void showMe() {
        std::cout << "Common showMe:" << payLoad << std::endl;
    }


   /*
    * A lot of functions same for all specializations go here.
    * I absolutely don't want to implement respectively them for
    * every specializations!
    */
};

template <typename T>
class AClass
    : public BaseClass<T> 
{  
public:
    AClass( const T& crp_payload )
        : BaseClass<T>(crp_payload)
    { }

};

// specializing for int ----------------------------
template<>
class AClass<int>
    : public BaseClass<int>
{
public:
    AClass( int crp_payload )
        : BaseClass(crp_payload)
    { }

   // dedicated function
   void showPayload() {
      std::cout << "AClass<int>::showPayload:" << payLoad << std::endl;
   }
private:
   int   otherPayload;
};

int main() {
   AClass<int> iac( 123 );
   iac.showMe();
   iac.showPayload();//can not pass the compiling!

   AClass<float> fac(456);
   fac.showMe();
   return 0;
}