【发布时间】:2020-01-05 18:07:25
【问题描述】:
我在某个文件中定义了以下 typedef:
typedef const uint8_t* BufType;
在另一个文件中,我需要删除指针的恒定性。我不能使用旧的 c 风格演员:(uint8_t*)。如何实现?
具体场景: 我有模板专业化来推断数据类型:
template<Enum E>
struct deduce_datatype_from {};
// Specialization
template<>
struct deduce_datatype_from<E1> {
typedef BufType const uint8_t*;
}
我在一个定义如下的函数模板中使用它:
template <Enum E>
void f(deduce_datatype_from<E>::BufType buf);
// function specialization.
template <>
void f<E1>(deduce_datatype_from<E1>::BufType buf) {
struct write_struct write_req;
write_req.buf = (??)buf;
}
在这种情况下,write_struct 由 lib 提供,但 buf 没有发生任何修改,因此应该是安全的。
【问题讨论】:
-
请注意,如果您将 const 从声明为 const 的对象中转换出来,然后写入该对象,您的程序将具有未定义的行为并且是无效程序并且编译器是 not 需要警告您,但可能会默默地生成损坏的代码。
-
如果您的
deduce_datatype_from不返回const,这不是更容易吗?毕竟,添加 const 非常简单。 -
您可以使用
std::remove_pointer,然后是std::remove_const,最后是std::add_pointer?这将为您提供不带const的指针。或者,您可以在分配之前取消引用指针并使用地址吗?
标签: c++ pointers templates constants