我正在寻找一种方式来配制具有类:转换STL容器<T *>集装箱<T const *>
- 使用最大“常量性”指针
- 但其中的STL容器的接口内部变异的尖-to对象
- 相比于一个非const模拟
理想的情况下没有额外的运行时开销,该解决方案将汇编没有分机ra代码与非const版本的比较,因为const/non-const-ness只是帮助程序员在这里。
这里是我试过到目前为止:
#include <list>
#include <algorithm>
using namespace std;
typedef int T;
class C
{
public:
// Elements pointed to are mutable, list is not, 'this' is not - compiles OK
list<T *> const & get_t_list() const { return t_list_; }
// Neither elements nor list nor' this' are mutable - doesn't compile
list<T const *> const & get_t_list2() const { return t_list_; }
// Sanity check: T const * is the problem - doesn't compile
list<T const *> & get_t_list3() { return t_list_; }
// Elements pointed to are immutable, 'this' and this->t_list_ are
// also immutable - Compiles OK, but actually burns some CPU cycles
list<T const *> get_t_list4() const {
return list<T const *>(t_list_.begin() , t_list_.end());
}
private:
list<T *> t_list_;
};
如果没有解决类型转换,我想就如何配制具有描述的属性的类其他建议。
'T const'不只是简单地转换为'T',你必须使用'const_cast',但这很丑陋,违反了const的要点。 – 2013-03-12 11:27:57
@Tony我想将'T'转换为'T const',这通常是可能的。以下编译:'int x = 2; int const * x_ptr =&x;' – SimonD 2013-03-12 11:39:54
不同的模板专业化是不相关的,它们是有效的不同类型。 – Xeo 2013-03-12 11:42:40