M
markus
I'm trying to work around the lack of static if. The use case is
something like:
---------------------------------------------------------------
struct A {
static const bool is_a = true;
int v1;
int v2;
int v3;
};
struct B {
static const bool is_a = false;
int v1;
static int v2; // dummy to make things compile
int v3;
};
template<class AorB>
class MyClass {
public:
void doSomething(AorB p) {
++p.v1;
if(AorB::is_a) ++p.v2;
++p.v3;
}
};
int main() {
MyClass<A> a; a.doSomething(A());
MyClass<B> b; b.doSomething(B());
}
---------------------------------------------------------------
Is there some better way to do that (C++11 is fine)?
Constraints:
- The memory layout must be exactly as above. Reordering of
fields or additional padding is a no-no.
- There can't be any run-time overhead.
- A/B must be trivially copyable.
- doSomething can't be decomposed into multiple or separate
functions. The vast majority of code is the same for the A or
B case and adding some utility function for handling v2 is
very messy.
something like:
---------------------------------------------------------------
struct A {
static const bool is_a = true;
int v1;
int v2;
int v3;
};
struct B {
static const bool is_a = false;
int v1;
static int v2; // dummy to make things compile
int v3;
};
template<class AorB>
class MyClass {
public:
void doSomething(AorB p) {
++p.v1;
if(AorB::is_a) ++p.v2;
++p.v3;
}
};
int main() {
MyClass<A> a; a.doSomething(A());
MyClass<B> b; b.doSomething(B());
}
---------------------------------------------------------------
Is there some better way to do that (C++11 is fine)?
Constraints:
- The memory layout must be exactly as above. Reordering of
fields or additional padding is a no-no.
- There can't be any run-time overhead.
- A/B must be trivially copyable.
- doSomething can't be decomposed into multiple or separate
functions. The vast majority of code is the same for the A or
B case and adding some utility function for handling v2 is
very messy.