繁体   English   中英

以下模板功能的含义是什么?

[英]Meaning of the following template function?

#define Create_Function(Type) \
    template void Function( std::vector<boost::shared_ptr<Type>>&)

Create_Function(std::string);

我在遗留代码中看到了上面的代码,但不知道它的含义是什么。 它既不是常规的非专用函数定义,也不是完整的专用函数定义。

任何的想法?

它进行显式模板实例化 (参见MSDN

显式实例化允许您创建模板化类或函数的实例化,而无需在代码中实际使用它。 因为在创建使用模板进行分发的库(.lib)文件时这非常有用,所以未将实例化的模板定义放入对象(.obj)文件中。

给出一般功能模板

template<typename T>
void Function( std::vector<boost::shared_ptr<T>>&)
{
    // bla bla
}

调用宏Create_Function(std::string); 将扩大到

template void Function( std::vector<boost::shared_ptr<std::string>>&);

这是函数模板的显式实例化。 给出一个模板:

template <typename T>
void Function( std::vector<boost::shared_ptr<T> >& );

(可能在头文件中声明并在.cpp文件中定义),代码:

template void Function( std::vector<boost::shared_ptr<int> >& );

要求编译器在此转换单元中实例化 (生成代码)特 这可以用于减少编译时间,因为模板的用户只需要查看模板的声明,并且不会在使用它的每个转换单元中实例化它。 在缺点方面,它要求对于与该模板一起使用的每种类型,在可以访问模板定义的转换单元中执行显式实例化,这限制了模板对这些实例的使用。

// tmpl.h
template <typename T>
void Function( std::vector<boost::shared_ptr<T> >& );

// tmpl.cpp
template <typename T>
void Function( std::vector<boost::shared_ptr<T> >& p ) {
    ... 
}
template void Function( std::vector<boost::shared_ptr<int> >& );
template void Function( std::vector<boost::shared_ptr<double> >& );

// user.cpp, user2.cpp, user3.cpp
#include <tmpl.h>
...
    std::vector<boost::shared_ptr<int> > v;
    Function( v );                             // [1]

在这个例子中,当编译'user#.cpp'时,我们不会在所有 使用它的翻译单元中实现Function模板的实例化成本,仅在'tmpl.cpp'中,这可能会减少编译时间。

有时候, 一面实际上是对这种方法的原因,你可以有效地限制实例类型的子集,你所提供的显式实例(即在上面的代码中,如果“userN.cpp”尝试调用Function传递共享指向std::string的向量链接器会抱怨)。

最后,在少数情况下,我已经看到它从图书馆的用户隐藏实际执行模板的时候才可以使用该类型的集合是有限的一种方式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM