3
有没有办法强制类的用户根据用于构造函数的数据构造const
对象?强制用户声明对象const
例如,考虑周围的一些缓冲小包装类,可以是const
或非const
class Wrapper {
public:
Wrapper(const char*);
Wrapper(char*);
};
现在,如果用户提供的是一个const
,我可以迫使他们声明对象是const
在编译时。那就是
// you have to do this if the input is const
const char* a;
// this will not compile
Wrapper w(a);
// but this will
const Wrapper(a);
任何想法?
不,没有办法做到这一点。 – john
对于工厂(函数),我认为有一种方法(绑定到const ref)。 – dyp
为什么不使用不可变包装?即一个不允许对包装对象进行更改的包装器。 – dyp