简体   繁体   中英

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> :

#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). 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);
            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

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?

I ran into this issue while trying to find the root cause for this StackOverflow question .

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".

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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