简体   繁体   中英

How to convert a struct into a template parameter pack?

Ok suppose I have a struct like so:

struct Example{
  uint8_t var0;
  uint32_t var1;
  uint16_t var2;
};

And suppose I have an instance (note constexpr) of the class that looks like this:

constexpr Example exp = {10,11,12};

And I want to somehow get the bit representation of this into a template parameter pack.

An example of what this would look like:

typedef SomeTemplate<
        /* first variable: 1 byte */   10,
        /* second variable: 4 bytes */ 11, 0, 0, 0,
        /* third variable: 2 bytes */  12, 0> mydef;

My knee jerk response to doing this is to do some template meta programming magic with some unions, but unfortunately this is not possible because accessing a union in the way I want is undefined behavior at compile time (ie error).

My ultimate goal with all of this is to put an instance of a user defined type into as a template parameter....something like this:

template<Example exp>
class OtherClass{
};

So the reason I am on this rabbit trail is I could take class Example and give a templated constructor which would take a list of uint8_t s in and then initialize itself that way (thus still constexpr and effectively allowing me to pass it in directly).

So is there any way to convert an arbitrary struct instance into an bit pattern at compile time (and all constexpr )?

Here is what I eventually ended up doing:

template<class T,class... Args_t>
struct Statifier{
    constexpr T operator()() { return T(Args_t()...); }
    constexpr operator T() { return T(Args_t()...); }
};

And then you use it like so:

template<class T, T value>
using ic = integral_constant<T,value>;
struct Point{
    int x;
    int y;
    int z;
    constexpr Point(int x,int y,int z) : x(x),y(y),z(z) { }
};
typedef Statifier<Point,ic<int,12>,ic<int,12>,ic<int,12> > triple;

triple is now a type and can be passed into a template parameter.

Limits of this approach:

  • You can only use types which can be differentiated by their constructors
  • You have to use types that have constexpr constructors
  • It can be cumbersome to initialize

But it is still awesome.

Thanks for you comments....they did help me find this method

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