为什么我不能static_cast一个包含void *的元组到一个包含char *的元组? [英] Why can't I static_cast a tuple containing a void* to one containing a char*?

查看:131
本文介绍了为什么我不能static_cast一个包含void *的元组到一个包含char *的元组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,我试图将static_cast a std::tuple<void*, size_t>转换为std::tuple<char*, size_t>:

In the below code, I'm trying to static_cast a std::tuple<void*, size_t> to a std::tuple<char*, size_t>:

#include <tuple>

int main() {
  char data[] = {'a', 'b', 'c'};
  size_t data_len = 3;

  const std::tuple<void*, size_t> a{static_cast<void*>(data), data_len};
  const std::tuple<char*, size_t> b =
      static_cast<const std::tuple<char*, size_t>>(a);
  printf("a's first element is %p\n", std::get<0>(a));
  printf("b's first element is %p\n", std::get<0>(b));
}

此代码无法使用g++ -std=c++17clang -std=c++17(使用最新的GCC和Clang版本)进行编译.在这两种情况下,编译器均指示无法完成静态转换.这是来自clang的示例错误:

This code does not compile with g++ -std=c++17 or clang -std=c++17 (with recent GCC and Clang versions). In both cases, the compiler indicates that the static cast can't be done. Here's an example error from clang:

main.cc:9:13: error: no matching conversion for static_cast from 'const std::tuple<void *, size_t>' (aka 'const tuple<void *, unsigned long>') to 'const std::tuple<char *, size_t>'
      (aka 'const tuple<char *, unsigned long>')
            static_cast<const std::tuple<char*, size_t>>(a);
            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

鉴于void*可以是static_castchar*,不是也可以将static_caststd::tuple<void*, size_t>std::tuple<char*, size_t>吗?这仅仅是STL设计中的一个疏忽,还是有一些潜在的原因?

Given that a void* can be static_cast to a char*, shouldn't it also be possible to static_cast a std::tuple<void*, size_t> to a std::tuple<char*, size_t>? Is this just an oversight in the design of the STL or is there some underlying reason for it?

我在尝试查找我要解决的问题是是的,很奇怪,您应该向C ++标准委员会发送一封措辞谨慎的电子邮件,建议他们在将来的C ++标准中解决此问题"或否,不需要此功能是没有道理的,因为X和Y".

What I'm trying to get out of this question is either "yes, that's weird, you should send a carefully worded email to the C++ standards committee suggesting that they fix this in a future C++ standard" or "no, it doesn't make sense to want this feature because X and Y".

推荐答案

一种解决方法是提供一个中间类,该中间类可以为您处理从std::tuple<void*, size_t>std::tuple<char*, size_t>的转换:

One way to work around this is to provide an intermediate class that can handle the conversion from std::tuple<void*, size_t> to std::tuple<char*, size_t> for you:

class TupleConverter : public std::tuple<char*, size_t> {
public:
  TupleConverter(const std::tuple<void*, size_t>& t) : std::tuple<char*, size_t>(
      static_cast<char*>(std::get<0>(t)), std::get<1>(t)) {}
};

然后您可以按以下方式使用它:

Then you can use it as follows:

const std::tuple<char*, size_t> b =
    static_cast<const TupleConverter>(a);

这篇关于为什么我不能static_cast一个包含void *的元组到一个包含char *的元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆