Select template argument at runtime in C++

前端 未结 3 1143
时光取名叫无心
时光取名叫无心 2020-12-15 10:54

Suppose I have a set of functions and classes which are templated to use single (float) or double precision. Of course I could write just two piece

相关标签:
3条回答
  • 2020-12-15 11:13

    No, you can't switch template arguments at runtime, since templates are instantiated by the compiler at compile-time. What you can do is have both templates derive from a common base class, always use the base class in your code, and then decide which derived class to use at runtime:

    class Base
    {
       ...
    };
    
    template <typename T>
    class Foo : public Base
    {
        ...
    };
    
    Base *newBase()
    {
        if(some condition)
            return new Foo<float>();
        else
            return new Foo<double>();
    }
    

    Macros have the same problem as templates, in that they are expanded at compile-time.

    0 讨论(0)
  • 2020-12-15 11:19

    Templates are purely a compile time construct, the compiler will expand a template and create your class/function with the specified argument and directly translate that to code.

    If you are trying to switch between foo<float> and foo<double> at runtime, you'll either need to use some metaprogramming trickery or just have seperate code paths for each.

    0 讨论(0)
  • 2020-12-15 11:26

    Templates are a compile-time mechanism. BTW, macros are as well (strictly speaking - a preprocessing mechanism - that comes even before compilation).

    0 讨论(0)
提交回复
热议问题