mercredi 1 novembre 2017

Make class member constexpr and store objects in stl container

I have a simple object with one variable. I'm storing some of these objects in a vector:

class Obj {
public:
  Obj(int i) : var(i) {}
  int var;
}
...
std::vector<Obj> v{Obj{1}, Obj{2}};

Now, for optimization purpose, I want to make var constexpr.

From what I understood, this implies that I need to make a template of Obj else all instances of my non-templatized classes are going to have the same value for var (which does makes sense).

So I do something like:

template<int v>
class Obj {
    public:
        constexpr int var() const {
            return v;
        }
};

And access var by calling the constexpr function. This is all good, except when I try to put Objs with different template values in a same vector.

I can not do std::vector<Obj> o{Obj<1>{}, Obj<2>{}} since the 2 objects have different types.

Anyone has an idea how to declare a class member constexpr for some instances of a given class and store them in an stl container please?

Note that:

  1. I don't want to use std::any as the conversion costs seem too high (and std::variant is unrealistic on int parameter AFAIK).
  2. I don't want to use polymorphism (cost of call to v-table)

Aucun commentaire:

Enregistrer un commentaire