I\'m trying to find an efficient way to invoke a specific C++ template type based dynamic value of a variable. Currently I\'m not clear on how to approach this, except by using
There’s no way (short of the very young JIT proposals) to avoid a branch or lookup table: it is a feature that different specializations of a function template can have unrelated types (with some restrictions on the parameter types, especially when supporting deduction), making it implausible to support a call with a dynamic template argument in the type system even if it were known to be drawn from a small set. (Yours all happen to be void(unsigned char*,const unsigned char*,int)
, but for consistency the rules do not consider that.)
That said, the boilerplate can be expressed efficiently in cases like this where the type doesn’t vary:
template<class D>
auto copier(int s) {
switch(s) {
case 1: return ConvertCopy<D,int>;
case 2: return ConvertCopy<D,unsigned>;
// …
}
}
void test() {
// …
[](int d) {
switch(d) {
case 1: return copier<int>;
case 2: return copier<float>;
case 3: return copier<double>;
// …
}
}(my_out_type)(my_in_type)(anyOut,anyIn,buffersize);
}
This approach reduces the verbosity to O(m+n) from O(mn). It may help if you think of the extra sets of parentheses as being separate because they are like “runtime template argument lists”.
It would of course be possible to generalize this to produce a value of any consistent type from a metafunction with (for practicality) a known range of interesting inputs.
MSVC compiles down to it's .NET
code (oversimplification), which allows you to use elements from other Microsoft languages. In Visual C++, there is a keyword known as 'generic` and it works like a template but may allow for what you're wanting.
Microsoft has a few pages of documentation on this, but here is the link to the overview page.