在模板专用化中添加单个构造函数方法

Add a single constructor method in template specialization

本文关键字:添加 单个 构造函数 方法 专用      更新时间:2023-10-16

我有以下类:

template <typename T>
class Fixed2DContainer {
    T* ptr;
public:
    const int total_cols;
    const int total_rows;
    Fixed2DContainer(int cols, int rows);
    T& operator()(int col_n, int row_n);
    ~Fixed2DContainer();
private : //disallow copy
    Fixed2DContainer& operator=(const Fixed2DContainer&);
    Fixed2DContainer operator()(const Fixed2DContainer&);
};

现在我想将这个模板专门用于某个类,以便唯一的变化是我可以拥有另一个构造函数。基本上我希望能够做到:

Fixed2DContainer<Image>("filename.jpg");

有没有一种优雅的方法可以做到这一点?我对模板相当陌生,所以我不知道难度

如果你的编译器支持它,C++11 有继承构造函数,这些构造函数几乎可以让你达到你想要的地方:

template <typename T>
class Base {};              // has all the implementation
template <typename T>
class Template {
   using Base::Base;
   //Template() = delete;   // You might need this if you don't want
                            // the default constructor
};
template <>
class Template<int> {
   using Base::Base;
   Template( std::string const & x ) {}
   //Template() = delete;   // You might need this if you don't want
                            // the default constructor
};

这是我在之前评论中的意思的快速示例......

template <typename T>
class Fixed2DContainerBase {
  T* ptr;
public:
  const int total_cols;
  const int total_rows;
  Fixed2DContainerBase(int cols, int rows);
  T& operator()(int col_n, int row_n);
  ~Fixed2DContainerBase();
private : //disallow copy
  Fixed2DContainerBase& operator=(const Fixed2DContainerBase&);
  Fixed2DContainerBase(const Fixed2DContainerBase&);
};
// primary template
template <typename T>
class Fixed2DContainer : public Fixed2DContainerBase<T> {
  Fixed2DContainer(int cols, int rows);
  ~Fixed2DContainer();
};
// explicit specialization
template <>
class Fixed2DContainer<Image> : public Fixed2DContainerBase<Image> {
  Fixed2DContainer(int cols, int rows);
  Fixed2DContainer(const std::string&);
  ~Fixed2DContainer();
};

注意:因为基类是不可复制的,所以派生类也是不可复制的。 如果基析构函数可以完成所有清理,则可能不需要在派生类中定义析构函数。

我自己也有同样的问题。遗憾的是,每个构造函数都必须存在于泛型模板中。不过,您可以避免人们在运行时使用错误的构造函数;

template <typename T>
class Fixed2DContainer {
    // omitted
    Fixed2DContainer(string fileName)
    {
        // Do not allow construction of Fixed2DContainer with
        // string argument in general case
        ASSERT(false);
        // or
        throw new ExceptionType("Not implemented");
    }
    // omitted
};
template<>
class Fixed2DContainer<Image> {
    // omitted
    Fixed2DContainer(string fileName)
    {
        // Actual construction code
    }
    // omitted
};
断言

是首选,因为您的代码将在断言上中断,而在异常情况下,它会在捕获时中断,从而使调试稍微困难一些。