Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select template argument at runtime in C++

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?

like image 735
Andrew T Avatar asked Mar 03 '09 22:03

Andrew T


3 Answers

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.

like image 168
Adam Rosenfield Avatar answered Oct 11 '22 00:10

Adam Rosenfield


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

like image 43
Nemanja Trifunovic Avatar answered Oct 10 '22 23:10

Nemanja Trifunovic


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.

like image 40
Ron Warholic Avatar answered Oct 10 '22 23:10

Ron Warholic