szukam sposób sformułować klasa posiadająca:Konwersja kontenera STL <T *> do pojemnika <T const *>
- interfejs użyciu kontenerów STL wskaźników z maksymalną „constness”
- ale które wewnętrznie mutuje szpiczaste -to obiektów
- bez dodatkowego okresie czasu w porównaniu do górnego const analogu
w idealnym rozwiązaniem byłoby, aby opracować nie wew kod ra w porównaniu do wersji niestałej, ponieważ const/non-const-ness jest tutaj po prostu pomocą dla programistów.
Oto, co starałem dotąd:
#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_;
};
Jeśli nie ma rozwiązania do konwersji typu, chciałbym alternatywne propozycje dotyczące sposobu formułowania klasy posiadające właściwości opisane.
'T const' nie jest po prostu zamieniany na' T', musisz użyć 'const_cast', ale to jest brzydkie i narusza punkt' const. –
@ Tony Chciałbym przekonwertować 'T' na' T const' chociaż, co jest normalnie możliwe. Następująca kompilacja: 'int x = 2; int const * x_ptr = & x; ' – SimonD
Różne specjalizacje szablonów nie mają związku, są to faktycznie różne typy. – Xeo