是否有内置方法可以强制转换为不同的基础类型,但保留常量限定符?



C++11/14/17 标准库是否有办法将对象转换为不同的类型,但具有与原始对象相同的 cv 限定符?

例如
char* ptr;
const char* cptr;

type_cast<void*>(ptr)应生成类型void*type_cast<void*>(cptr)
应生成类型const void*

不在标准库中,但肯定可以自己实现:

namespace detail_base_type_cast {
template <class In, class Out>
struct copy_cv {
using type = Out;
};
template <class In, class Out>
struct copy_cv<In const, Out &> {
using type = Out const &;
};
template <class In, class Out>
struct copy_cv<In volatile, Out &> {
using type = Out volatile &;
};
template <class In, class Out>
struct copy_cv<In const volatile, Out &> {
using type = Out const volatile &;
};
}
template <class Out, class In>
typename detail_base_type_cast<In, Out>::type
base_type_cast(In &obj) {
return obj; // Implicit derived-to-base conversion
}

看起来没有 C++17 或更早的 stdlib 方法可以在单个函数/语句中执行您想要的操作。 但是,看起来在 C++20:https://en.cppreference.com/w/cpp/types/common_reference 中可能有这样的东西(似乎在任何编译器中都不可用(。

编辑:但它在范围库中可用,所以如果你已经使用它,你可以改用ranges::common_reference_t

但是对于您的用例,重载参数恒常性或使用if constexpr可能是更好的选择。

即像这样:

template<typename T>
auto foo(T &bar) {
// lots of code
if constexpr(std::is_const_v<T>) {
return static_cast<const Foo&>(bar);
} else {
return static_cast<Foo&>(bar);
}
}

https://godbolt.org/z/dbCUdM

最新更新