C++ template usage based on selecting type dynamically

前端 未结 2 1346
无人及你
无人及你 2021-01-25 14:06

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

2条回答
  •  天命终不由人
    2021-01-25 14:31

    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
    auto copier(int s) {
      switch(s) {
      case 1: return ConvertCopy;
      case 2: return ConvertCopy;
      // …
      }
    }
    void test() {
      // …
      [](int d) {
        switch(d) {
        case 1: return copier;
        case 2: return copier;
        case 3: return copier;
        // …
        }
      }(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.

提交回复
热议问题