c++ - Switch statements and integer template values -
i aware if instantiate template such as:
template<int i> int returnmedouble() { return 2 * i; } then compiler needs able evaluate value of @ compile time. problem (dumbed down simplicity) want program call 1 of 2 functions depending on variable. code looks this:
int returnvalue = 0; switch(value) { case 1: case 2: case 3: case 4: returnvalue = returnmedouble<value>(); break; case 5: case 6: returnvalue = returnmetriple<value>(); break; } the real returnme... functions less trivial. obviously, use switch statement , provide individual calls under each case statement, wondering if there i'm missing, since seems obvious me (if not compiler) in first case, returnmedouble can called 1 of 4 values.
is compiler have put in conditional flow around 4 separate function templates need instantiating (effectively i'm trying avoid doing manually) , doesn't know how to?
is there more elegant way of doing this?
edit: clarify - less trivial implementation uses integer value apply metaprograms type selection within function.
i think you've pretty nailed attempted explanation.
the standardese way of looking @ things value supply template argument must constant known @ compile time. since value you've supplied variable that's not known until run-time, it's not allowed.
yes, in specific case, compiler decent optimizer figure out 4 constant values need supplied 4 cases you've given.
there quite few more cases lot less clear-cut though. example, cases compiler incorporates specific optimization can figure out particular value compile-time constant, lacking particular optimization won't know it.
faced question couldn't answer ("can compiler deduce value @ compile time?") committee took conservative approach, , specified relatively narrow range of allowable inputs. compiler could, of course, choose accept other expressions extension.
from committee's viewpoint, think adding constexpr attempt @ general implementation of @ least similar -- allowing larger range of computation done in way lets compiler know result should available compile-time constant. given complexity of implementing that, guess mandating compile-time computation cases you've given above unlikely (at least near future).
Comments
Post a Comment