在C++中运行时选择模板参数

And*_*w T 9 c++ templates arguments runtime

假设我有一组模板使用single(float)或doubleprecision 的函数和类.当然,我只能写两段引导代码,或者乱用宏.但我可以在运行时切换模板参数吗?

Ada*_*eld 20

不,您无法在运行时切换模板参数,因为模板在编​​译时由编译器实例化.你可以做的是让两个模板派生自一个公共基类,总是在你的代码中使用基类,然后决定在运行时使用哪个派生类:

class Base
{
   ...
};

template <typename T>
class Foo : public Base
{
    ...
};

Base *newBase()
{
    if(some condition)
        return new Foo<float>();
    else
        return new Foo<double>();
}
Run Code Online (Sandbox Code Playgroud)

宏与模板具有相同的问题,因为它们在编译时扩展.