在模板专用化中添加单个构造函数方法
Add a single constructor method in template specialization
我有以下类:
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
};
断言是首选,因为您的代码将在断言上中断,而在异常情况下,它会在捕获时中断,从而使调试稍微困难一些。
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 如何在C++中从两个单独的for循环中添加两个数组
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 如何仅为一个函数添加延迟
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 替换为单个黑斜杠在Qt中添加"
- 如何防止 clang 格式向新行添加单个分号
- MFC Applicaton:如何将一组控件添加到单个文档应用程序中
- 删除 max 并添加新元素 c++ std::make_heap 时进行单个'Heapify'调用
- 为什么为结构的多个数据成员而不是单个成员添加填充
- 如何使用c++将所有类的执行时间添加到单个文本文件中
- 在模板专用化中添加单个构造函数方法
- 如何在win32程序中在单个窗口中添加多个工具栏
- 如何将QActions列表添加到QMenu并用单个插槽处理它们
- 添加到单个数组元素-C++
- 在Qt中,我如何在for循环中添加qstring,以相互附加并放入单个消息框中
- 如何在OpenGL地形上添加单个纹理
- XCode:如何为单个源文件添加预处理器定义
- 如何基于单个用户定义的文字自动添加文字定义
- 如何将多个图标添加到单个TreeView项