我有一个可以(有时必须)采用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;
}
Run Code Online (Sandbox Code Playgroud)
因为即使在构造函数期间 val 上有一个副本,它也会复制到相同的类型 - const int。就像你可以在模板中区分T和一样const T,有没有办法区分T和“ nonconst T”?
SomeClass<typename std::remove_const<T>::type> other()
{
return SomeClass<typename std::remove_const<T>::type>(val);
}
Run Code Online (Sandbox Code Playgroud)
std::remove_const来自<type_traits>并且是 C++11。boost::remove_constBoost.TypeTraits 中可能有一个,或者您甚至可以推出自己的。也可以使用std::remove_cv.