在模板中获取非const类型

时间:2012-02-29 18:39:48

标签: c++ templates

我有一个模板类,可以(有时必须)采用const类型,但是有一个方法可以返回具有相同类型的类的新实例,但应该显式为非const 。例如,以下代码无法编译

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;
}

因为即使在构造函数中有val的副本,它也会复制到相同的类型 - const int。就像您可以在模板中区分Tconst T一样,有没有办法区分T和“nonconst T”?

3 个答案:

答案 0 :(得分:4)

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

std::remove_const来自<type_traits>,是C ++ 11。 Boost.TypeTraits中可能有boost::remove_const,您甚至可以自己滚动。{1}}。也可以使用std::remove_cv

答案 1 :(得分:4)

如果您使用的是c ++ 11,则可以使用std::remove_const。否则,您可以使用:

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

其中也是如此。

答案 2 :(得分:0)

问题本质上是有两种不同的类型,它们不是严格可转换的。

您可以在type_traits中使用/ return std::remove_const

#include <type_traits>

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

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

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