I have a simple object with some variables. I'm storing some of these objects in a array:
class Obj {
public:
Obj(int i, int j) : var(i), var2(j) {
obj.initialize(); //or something
}
int var, var2;
MyOtherNonConstExprObject obj;
}
...
std::array<Obj> v{Obj{1,2}, Obj{3,4}};
Now, for optimization purpose, I want to make var
constexpr. Note that I can't make my whole object/constructor constexpr
since MyOtherNonConstExprObject is not known at compile time.
My end goal is to be able to do something like that at compile time (my hot path is full of those tests):
if constexpr(v[0].var == v[1].var) {
...
}
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, int w>
class Obj {
public:
constexpr int var() const {
return v;
}
constexpr int var2() const {
return w;
}
....
};
And access var by calling the constexpr function.
This is all good, except when I try to put Obj
s with different template values in a same vector.
I can not do constexpr const std::array<Obj> o{Obj<1,2>{}, Obj<3,4>{}}
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:
- I don't want to use std::any as the conversion costs seem too high (and std::variant is unrealistic on int parameter AFAIK).
- I don't want to use polymorphism (cost of call to v-table)
Edit: change vector to array, add second template parameter.