【发布时间】:2011-11-20 03:19:31
【问题描述】:
我正在编写一组 C++ 参数化类,我对其中一些行为类似于指针的类感兴趣。特别是,我希望能够从具有非常量模板参数的对象创建具有常量模板参数的对象,但不能反过来。此示例代码应阐明我的意图:
int main() {
myClass<int> mc_int;
myClass<const int> mc_const_int;
myClass<const int> mc1(mc_const_int); // This should compile.
myClass<int> mc2(mc_int); // This should compile.
myClass<const int> mc3(mc_int); // This should compile.
myClass<int> mc4(mc_const_int); // This should NOT compile.
}
我已经能够通过创建下一个类层次结构来实现这种特殊行为(为了便于阅读而进行了简化):
template <typename T>
class Base {
// ...
protected:
template <typename U>
Base(const Base<U> &obj): _elem(obj._elem) {}
private:
T _elem;
friend class Base<const T>;
};
template <typename T>
class myClass: public Base<T> {
// ...
public:
template <typename U>
myClass(const myClass<U> &obj): Base<const U>(obj) {}
};
它按预期工作,但我对这个设计并不完全满意,因为我只能从构造函数中检测到非常量模板参数,而不能从任何其他成员函数中检测到。
例如,如果我想用addAll() 方法创建一个容器类,我希望能够这样做:
int main() {
Container<int> c_int;
c_int.add(new int(1));
c_int.add(new int(2));
c_int.add(new int(3));
Container<const int> c_const_int;
c_const_int.addAll(c_int); // This should compile.
c_int.addAll(c_const_int); // This should NOT compile.
}
但我不知道如何实现以前的行为。有没有人有替代设计的想法来实现我想要做的事情?有谁知道更深入讨论这个问题的链接?
提前致谢。
【问题讨论】:
标签: c++ templates pointers constants class-design