Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"const const T" in template

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?

like image 284
SigTerm Avatar asked Dec 05 '22 19:12

SigTerm


2 Answers

If T = const int *, then const T is const int * const.

like image 51
Kerrek SB Avatar answered Dec 30 '22 22:12

Kerrek SB


We can translate

const int *

into

int const *

A pointer to a constant int. When you have T=int*, what you have with const T is:

int * const

Which means, a constant pointer to a int.

So in your case with T=const int*, which is int const *, what you have with const T is:

int const * const

Which means a constant pointer to a constant int. Which is legal.

If it is not the desired behavior, you may have partial specialization, like:

template<typename T> struct A<const T>{
//here comes different implementation for the case where A template is
//initialized with a const type.
like image 45
André Puel Avatar answered Dec 30 '22 22:12

André Puel