The following code compiles and works on G++ 4.4.0 and MS VC2008 Express.
#include <iostream>
template<typename T> struct A{
protected:
T v;
public:
const T get() const{
return v;
}
A(T v_)
:v(v_){
}
};
class B: public A<const int*>{
public:
void doSomething() const{
const int* tmp = get();
std::cout << *tmp << std::endl;
}
B(const int* p)
:A<const int*>(p){
}
};
int main(int argc, char** argv){
int a = 134;
B b(&a);
const B& c = b;
b.doSomething();
c.doSomething();
return 0;
}
However, as I understand it using A<const int*> should result in const const int* A::get() const;. And I’m pretty sure I haven’t seen anything like that in real code. Is using template in such way “legal”?
If not, what are alternatives? In my code I need a template class that provides two “getter” methods (const/non-const), and can take a “const int*” as a type. Something like this:
template<typename T> struct A{
protected:
T v;
public:
const T get() const{
return v;
}
T get(){
return v;
}
A(T v_)
:v(v_){
}
};
Any ideas?
If
T = const int *, thenconst Tisconst int * const.