模板专业化中的额外方法

Ric*_*ard 6 c++ templates

我正在尝试使用一些方法/运算符等来编写模板化的类.现在,当类具有特定类型时,我希望有额外的追加方法,特别适用于那种类型,不适用于任何其他类型.我不想将所有代码复制到一个新类中.

例:

template<typename T>
class Buffer
{
    Buffer(const Buffer<Type> &Buffer) : mData(Buffer.mData)
    {               
    }

    Buffer<Type> Clone()
    {
    }

    void Append (T * aData)
    {
    }

    // this one should only be there when Type is an unsigned char
    void Append (wchar_t * aData)
    {
    }

}
Run Code Online (Sandbox Code Playgroud)

这是可能吗?

格雷茨,理查德.

Arm*_*yan 8

直接这是不可能的.完全专业化是完全专业化,这意味着您必须从头开始实现专业化的类.但是我可以建议以下技巧:

template<class T>
class CommonFunctionality
{
   //your methods here
};

template<class T>
class MyClass: public CommonFunctionality<T>
{
};

template<>
class MyClass<MyType>:public CommonFunctionality<MyType>
{
  public:
    //your extra method here
};
Run Code Online (Sandbox Code Playgroud)

感谢Mark的建议,以下是使用clone方法可以做的事情:

template<class T, class ActualType>
class CommonFunctionality
{
   //your methods here
   ActualType Clone(){...}
};

template<class T>
class MyClass: public CommonFunctionality<T, MyClass<T> >
{
};

template<>
class MyClass<MyType>:public CommonFunctionality<MyType, MyClass<MyType> >
{
  public:
    //your extra method here
};
Run Code Online (Sandbox Code Playgroud)

  • 或者使用带有额外模板参数的CRTP到`CommonFunctionality`类. (3认同)

Nim*_*Nim 1

使用策略类来管理与类型的交互,那么您的类实际上不必担心传入的类型,适当的策略(以及所述策略的专门化)可以包含特定于该类型的所有逻辑。

#include <iostream>
#include <vector>

template <typename T, typename U>
struct append_policy
{
  template <typename BufferType>
  static void append(BufferType& buffer, U type)
  {
    std::cout << "default: append U" << std::endl;
  }
};

template <typename U>
struct append_policy<std::string, U>
{
  template <typename BufferType>
  static void append(BufferType& buffer, U type)
  {
    std::cout << "string: append U" << std::endl;
  }
};

template <>
struct append_policy<std::string, char>
{
  template <typename BufferType>
  static void append(BufferType& buffer, char type)
  {
    std::cout << "string: append char" << std::endl;
  }
};

template <typename T>
struct foo
{
  template <typename U>
  void append(U a)
  {
    append_policy<T, U>::append(buffer, a);
  }

  std::vector<char> buffer;
};

int main(void)
{
  foo<std::string> f;
  std::string test("test");
  f.append(test);
  f.append('C');

  foo<int> f1;
  f1.append(0);

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

编辑:现在允许您将任何类型附加到任何类型MyClass,并允许您覆盖特定的类型组合,并可能在您不希望支持的其他组合中引发异常。