简体   繁体   English

为什么我不能static_cast一个包含void *的元组到一个包含char *的元组?

[英]Why can't I static_cast a tuple containing a void* to one containing a char*?

In the below code, I'm trying to static_cast a std::tuple<void*, size_t> to a std::tuple<char*, size_t> : 在下面的代码,我想static_cast一个std::tuple<void*, size_t>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));
}

This code does not compile with g++ -std=c++17 or clang -std=c++17 (with recent GCC and Clang versions). 此代码无法与g++ -std=c++17clang -std=c++17 (具有最新的GCC和Clang版本)一起编译。 In both cases, the compiler indicates that the static cast can't be done. 在这两种情况下,编译器均指示无法完成静态转换。 Here's an example error from clang : 这是来自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);
            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

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> ? 考虑到一个void*可以static_castchar* ,应该不是也有可能static_cast一个std::tuple<void*, size_t>std::tuple<char*, size_t> Is this just an oversight in the design of the STL or is there some underlying reason for it? 这仅仅是STL设计中的一个疏忽,还是有一些潜在的原因?

I ran into this issue while trying to find the root cause for this StackOverflow question . 我在尝试查找此StackOverflow问题的根本原因时遇到此问题

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". 我要解决的问题是“是的,这很奇怪,您应该向C ++标准委员会发送一封措辞谨慎的电子邮件,建议他们在将来的C ++标准中解决此问题”或“否,这不是想要此功能很有意义,因为X和Y”。

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: 解决此问题的一种方法是提供一个中间类,它可以为您处理从std::tuple<void*, size_t>std::tuple<char*, size_t>的转换:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM