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?
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.
Templates are a compile-time mechanism. BTW, macros are as well (strictly speaking - a preprocessing mechanism - that comes even before compilation).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With