首先,为术语道歉 - 我不确定模板原型(prototype)是否是正确的术语。我的意思是:
template <class T, class X>
class TemplatePrototype
{
// code
};
我有一种情况,我有一个函数,它根据该函数的模板参数创建一个模板对象。
template <class T, class X>
void doSomething()
{
TemplatePrototype<T, X> aTemplateTX;
aTemplateTX.doSomethingElse();
}
但是TemplatePrototype大约有15个不同的版本,它们的接口(interface)相同但执行不同(TemplatePrototype由另一个库提供)。结果,我有很多看起来像这样的代码:
template <class T, class X>
void doSomethingWithOne()
{
TemplatePrototypeOne<T, X> aTemplateTX;
aTemplateTX.doSomethingElse();
}
template <class T, class X>
void doSomethingWithTwo()
{
TemplatePrototypeTwo<T, X> aTemplateTX;
aTemplateTX.doSomethingElse();
}
作为体系结构的结果,我必须知道我要使用哪个TemplatePrototype,在我知道实际类型T 和X 之前。我会喜欢 看到这样的东西:
template <class T, class X, class Prototype>
void doSomething()
{
Prototype<T, X> aPrototype;
aPrototype.doSomething();
}
但是我预先指定了部分模板参数 - 即我在知道 T 和 X 之前指定了原型(prototype)。显然,这在 C++ 中是不可能的。
同样,我不能将原型(prototype)作为模板参数传递,因为它仍然会导致大量重复代码。
一些重要的事实:我知道所有可能输入的范围。
因此理论上我可以使用宏来定义每个可能的模板特化并将它们插入容器中,然后我将使用它来访问我需要的特化。但是,我正在寻找一个更“优雅”的解决方案——是否可以传递模板原型(prototype)而不将它们专门化为模板类的参数,然后在调用函数时实例化?示例:
template <class Prototype>
class Holder
{
template <class T, class X>
void doSomething()
{
Prototype<T, X> aPrototype;
aPrototype.doSomethingElse();
}
};
据我所知这是不可能的,但我想知道 SO 社区是否有一些人知道解决方案?
编辑:
因此,由于以下答案,我已将此作为我的解决方案实现!
#include <iostream>
template <typename T>
struct Foo
{
Foo() { aPtr = 0; }
T* aPtr;
};
template <template<typename> class C>
struct Bar
{
template <class T>
void doSomething()
{
C<T> aClass;
if (aClass.aPtr)
std::cout << "Hello world" << std::endl;
}
};
int main()
{
Bar<Foo> aFoo;
aFoo.doSomething<int>();
return 0;
}
这使我能够在知道模板参数之前指定我希望使用的 TemplatePrototype。
最佳答案
是的,使用模板模板参数,例如
template <typename T>
struct Foo
{
};
template <template<typename> class C>
struct Bar
{
};
然后
Bar<Foo> b;
关于c++ - 将模板原型(prototype)作为模板参数传递——这可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28807605/