Is it possible to choose a C++ generic type parameter at runtime?

后端 未结 5 716
天命终不由人
天命终不由人 2021-02-14 07:52

Is there a way to choose the generic type of a class at runtime or is this a compile-time thing in C++?

What I want to do is something like this (pseudocode):

         


        
5条回答
  •  佛祖请我去吃肉
    2021-02-14 08:25

    It's a compile time thing. Template parameter types must be known to the compiler at compile-time.

    That being, said, using certain template meta-programming techniques, you can choose one type or another AT compile-time, but only if all possible types are known at compile-time, and only if the condition for selecting a type can be resolved at compile time.

    For example, using partial specialization you could select a type at compile time based on an integer:

    template 
    class Foo
    { };
    
    template 
    struct select_type;
    
    template<>
    struct select_type<1>
    {
        typedef int type;
    };
    
    template<>
    struct select_type<2>
    {
        typedef float type;
    };
    
    int main()
    {
        Foo::type> f1; // will give you Foo
        Foo::type> f2; // will give you Foo
    }
    

提交回复
热议问题