Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting non-const type in template

Tags:

c++

templates

I have a template class that can (and sometimes has to) take a const type, but there is a method that returns a new instance of the class with the same type, but should be explicitly non-const. For example, the following code fails to compile

template<class T> class SomeClass {
public:
    T val;
    SomeClass(T val) : val(val) {}
    SomeClass<T> other() {
        return SomeClass<T>(val);
    }
};

int main() {
    SomeClass<const int> x(5);
    SomeClass<int> y = x.other();
    return 0;
}

because even though there's a copy on val during the constructor, it's copying to the same type - const int. Just like you can distinguish between T and const T in a template, is there a way to distinguish between T and "nonconst T"?

like image 885
Mike Barriault Avatar asked Feb 29 '12 18:02

Mike Barriault


2 Answers

SomeClass<typename std::remove_const<T>::type> other()
{
    return SomeClass<typename std::remove_const<T>::type>(val);
}

std::remove_const is from <type_traits> and is C++11. There's probably a boost::remove_const in Boost.TypeTraits, or you can even roll your own. It's also possible to use std::remove_cv.

like image 115
Luc Danton Avatar answered Oct 21 '22 14:10

Luc Danton


You can either use std::remove_const if you are using c++ 11. Otherwise, you can use this:

struct <typename T>
struct remove_const
{
    typedef T type;
};
struct <typename T>
struct remove_const<const T>
{
    typedef T type;
};

Which does the same.

like image 31
PierreBdR Avatar answered Oct 21 '22 16:10

PierreBdR