【发布时间】:2021-05-17 19:30:43
【问题描述】:
我正在学习模板。如果我混淆了模板/模板类型/模板参数的概念,请纠正我。
我正在尝试编写一个模板函数来创建一个对象并返回它。对象的类型来自必须显式指定的模板参数。
result = createObject<ObjectType>();
这个对象虽然应该是一个模板。以容器为例。并且该函数应该知道对象的类型及其模板参数。例如:
result = createObject<Container<ElementType>>();
我已经尝试使用模板模板参数来解决它:
template <template<class> class ContainerType, class ElementType>
auto createObject()
{
ContainerType<ElementType> result;
//do stuff...
return result;
}
//...
template<typename T>
struct Vector{};
//...
//const auto random_vec = createObject<Vector<float>>(); // ERROR.
const auto random_vec = createObject<Vector, float>();
第二种情况有效,第一种无效。上面写着candidate template ignored: invalid explicitly-specified argument for template parameter 'ContainerType'。
是否有可能让它像第一种情况一样工作?给它Vector<float> 之类的东西,它可以推断ContainerType 到Vector 和ElementType 到float?是否可以重载或专门化此功能,以便它以不同的方式处理某些类型的容器?我应该使用概念吗?
【问题讨论】:
-
不是“createObject()”只是一个函数而不是一个类,结构吗?缺少分号。
-
所以
createObject需要区分要创建的类型是模板的特化而不是像int这样的简单类型的情况? -
@DavisHerring 是的。
-
既然您要求更正:“模板函数”是过时的术语。既然不是一种函数而是一种模板,那就用“函数模板”(虽然更一般的“模板化函数”也有意义)。
标签: c++ templates c++-concepts