Home > Net >  create span of strong type from a vector of the underlying type
create span of strong type from a vector of the underlying type

Time:09-01

If I have a strong type wrapper for example:

struct StrongType {
  double val;
};

std::vector<double> v;

Is there any valid way to view the underlying type vector as if it were the strong type?

For example something like the following but without undefined behavior (and without copying):

std::span<StrongType> strong_span(reinterpret_cast<StrongType*>(v.data()), v.size());

Based on my understanding of the aliasing rules this is UB since StrongType is not similar to double.

Edit: The reason I'm asking this is because I am working on an abstraction layer over a third party library. The third party library gives data back in a format roughly equivalent to a std::vector<double> and in the higher level abstraction there is certain compile time data that should tagged via the strong time. An example of this would be the coordinate system (for point data) and memory location (i.e., cuda memory vs. host memory).

CodePudding user response:

There are no exceptions to the aliasing/type punning rules for the case presented with a class with a single data member for conversion to the type of that data member.

Therefore a data copy (possibly using memcpy or bit_cast) must take place to accomplish this.

CodePudding user response:

The best you can do is to construct your StrongType objects on the fly. Ted Lyngmo provided code that does this with additional wrapper types, but a simple version can be implemented with just the Ranges library:

for(StrongType st :
    std::views::transform(v,[](double d) {return StrongType{d};})) …

The result is a random-access range, though not a contiguous one (since it doesn’t yield references), and its iterators are merely C 17 input iterators.

  • Related