gpt4 book ai didi

c++ - 如何使用 const/nonconst 指针/引用参数模板化函数

转载 作者:行者123 更新时间:2023-11-30 03:30:35 26 4
gpt4 key购买 nike

假设我有以下一组函数:

typedef uint8_t byte;

inline byte *as_bytes(char *data) {
return reinterpret_cast<byte*>(data);
}

inline byte *as_bytes(std::vector<byte> &v) {
return &v[0];
}

inline byte *as_bytes(QByteArray &a) {
return as_bytes(a.data());
}

inline const byte *as_cbytes(const char *data) {
return reinterpret_cast<const byte*>(data);
}

inline const byte *as_cbytes(const std::vector<byte> &v) {
return &v[0];
}

inline const byte *as_cbytes(const QByteArray &a) {
return as_cbytes(a.data());
}

问题:我能否模板化这些函数,以便常量性和指针/引用类型推导能够正常工作?我想看到的结果可能如下所示:

template<typename T>
inline byte *as_bytes(T data) {
return reinterpret_cast<byte*>(data);
}

template<>
inline byte *as_bytes(std::vector<byte> &v) {
return &v[0];
}

template<>
inline byte *as_bytes(QByteArray &a) {
return as_bytes(a.data());
}

当然,由于两个原因,这段代码对我不起作用:

  • 我希望推导出参数的常量性并将其转发给返回类型;
  • 由于我们讨论的是函数,所以专门针对 std::vectorQByteArray不会像预期的那样工作,因为总是template<typename T> inline byte *as_bytes(T data)将因为功能过载而被选中。

也许有一些 C++11/14/17 机制可以解决这些问题并最终得到 3 个漂亮的函数?

最佳答案

这可能适合您的需求:

template<typename T>
inline auto as_bytes(T *data) {
return reinterpret_cast<
typename std::conditional<std::is_const<T>{}, const byte*, byte*>::type
>(data);
}

template <typename T>
inline auto as_bytes(T &t) -> decltype(as_bytes(t.data())) {
return as_bytes(t.data());
}

这是如何工作的:

  • 第一个模板函数采用 T* 以便 (const) 引用 std::vector/QByteArray(或您可以添加的任何其他类型)永远不会匹配此模板,并且常量是使用 std::conditionalstd::is_const 的组合从 T 推导出来的.

  • 第二个模板函数将匹配具有成员函数 data() 的任何类型 T(std::vector 就是这种情况(自 C++11 起)和 QByteArray),并且由于 T::data 具有 const 重载而推导出常量。

    <

在第二个函数中使用尾随返回类型将允许您为不提供 .data() 方法的类型添加额外的重载,而不会产生歧义。

关于c++ - 如何使用 const/nonconst 指针/引用参数模板化函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44861527/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com