views:

561

answers:

3

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 pieces of bootstrap code, or mess with macros. But can I just switch template argument at runtime?

+1  A: 

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

Nemanja Trifunovic
+11  A: 

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.

Adam Rosenfield
+1  A: 

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.

Ron Warholic