Extract C++ template parameters

前端 未结 5 1785
轻奢々
轻奢々 2020-12-05 13:26

Although I\'m doubtful, I\'m curious as to whether it\'s possible to extract primitive-type template parameters from an existing type, perhaps using RTTI.

For exampl

5条回答
  •  臣服心动
    2020-12-05 13:52

    It's not possible in general to pick arbitrary template parameters.

    However, the usual way you do it is this:

    template
    struct foo {
        static const int value = N;
    };
    

    and for types

    template
    struct foo {
        typedef T type;
    };
    

    You can access it then as foo<39>::value or foo::type.

    If you have a particular type, you can use partial template specialization:

    template
    struct steal_it;
    
    template
    struct steal_it< std::bitset > {
        static const std::size_t value = N;
    };
    

    The same principle is possible for type parameters too, indeed. Now you can pass any bitset to it, like steal_it< std::bitset<16> >::value (note to use size_t, not int!). Because we have no variadic many template paramters yet, we have to limit ourself to a particular parameter count, and repeat the steal_it template specializations for count from 1 up to N. Another difficulty is to scan types that have mixed parameters (types and non-types parameters). This is probably nontrivial to solve.

    If you have not the type, but only an object of it, you can use a trick, to still get a value at compile time:

    template
    char (& getN(T const &) )[steal_it::value];  
    
    int main() {
        std::bitset<16> b;
        sizeof getN(b); // assuming you don't know the type, you can use the object
    }
    

    The trick is to make the function template auto-deduce the type, and then return a reference to a character array. The function doesn't need to be defined, the only thing needed is its type.

提交回复
热议问题