【发布时间】:2019-06-07 03:53:07
【问题描述】:
我定义了一个模板函数,想根据不同的输入调用不同的特化:
// 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++