gpt4 book ai didi

c++ - 如何根据运行时输入实例化c++模板?

转载 作者:搜寻专家 更新时间:2023-10-31 00:25:16 25 4
gpt4 key购买 nike

我定义了一个模板函数,想根据不同的输入调用不同的特化:

// function
template <typename T>
void f() {...}

// specialization 1
template <>
void f<C1>() { ... }

// specialization 2
template <>
void f<C2>() { ... }


// class
class Cbase {};

class C1 : Cbase {};

class C2 : Cbase {};

int main()
{
std::string s = input();
Cbase* c;

if (s == "c1")
{
// here I want to use `specialization 1` but not
// call immediately here but later, so I create an instance of C1
c = new C1;
}
else
{
// here I want to use `specialization 2` but not
// call immediately here but later, so I create an instance of C2
c = new C2;
}

// Is there a way to call specializations according to the type of `c`?
// Can I get the type in the runtime to call the particular
// template specializations I want?
}

有没有办法根据c调用特化?我能否在运行时获取类型以调用我想要的特定模板特化?

最佳答案

没有。根据定义,模板是编译时构造。如果您需要运行时多态性,那么您基本上应该关注虚函数。

关于c++ - 如何根据运行时输入实例化c++模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56487736/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com