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?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
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>
andfoo<double>
at runtime, you'll either need to use some metaprogramming trickery or just have seperate code paths for each.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:
Macros have the same problem as templates, in that they are expanded at compile-time.