在 C++ 中在运行时选择模板参数 [英] Select template argument at runtime in C++

查看:42
本文介绍了在 C++ 中在运行时选择模板参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一组函数和类,它们被模板化为使用单精度 (float) 或 double 精度.当然,我可以只写两段引导程序代码,或者弄乱宏.但是我可以在运行时切换模板参数吗?

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.

这篇关于在 C++ 中在运行时选择模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆