lundi 31 août 2020

assign a templated variable at runtime

I have some code that worked great until now but there is a new change that is breaking it. Looking for ideas on how to deal with it. I am not a C++ template expert and have basic working knowledge.

namespace foo {
enum {
ITEM0,
ITEM1,
..
ITEMN
};

constexpr int A = 
#if defined(SOME_DEFINE1)
A1,
#elif defined(SOME_DEFINE2)
A2,
...
#elif defined(SOME_DEFINEN)
AN
#endif
;

// Then I have some variables that depend on A
template<int> struct var1;
template<>struct var1<A1> { static constexpr auto value = v1; }
template<>struct var1<A2> { static constexpr auto value = v2; }
template<>struct var1<A3> { static constexpr auto value = v3; }

template<int> struct var2;
template<>struct var2<A1> { static constexpr auto value = x1; }
template<>struct var2<A2> { static constexpr auto value = x2; }
template<>struct var2<A3> { static constexpr auto value = x3; }
} // namespace foo

constexpr auto VAR1 = foo::var1<foo::A>::value;
constexpr auto VAR2 = foo::var2<foo::A>::value;

now VAR1 and VAR2 are used in multiple places. I understand that all of this code will be optimized by the compiler and things work.

Now because of the new change I can only know the value of 'A' at runtime and as a result cannot declare is at constant anymore. A will be determined from a value of a global variable somewhere. Any ideas on how to implement this so I make very minimal changes to my code.

Let us say there is a gVal which can be 1,2 or 3 and based on that I want to set A to be A1,A2 or A3 which affect the values of other variables. Any help is greatly appreciated.

Aucun commentaire:

Enregistrer un commentaire