[英]Explicit template instantiation with variadic templates
I have several template classes Impl
(with some abstract methods) that are partially implemented in CPP files so that I need to explicitly instantiate my templates for the linker to find it, like this:我有几个模板类
Impl
(带有一些抽象方法)在 CPP 文件中部分实现,因此我需要显式实例化我的模板以便链接器找到它,如下所示:
template class Impl<T0>;
template class Impl<T1>;
template class Impl<T2>;
...
template class Impl<Tx>;
As the number of types Tx
grows, I would like to find a better way than to manually expand these lists of explicit instantiations in all necessary files.随着
Tx
类型数量的增加,我想找到一种比在所有必要文件中手动扩展这些显式实例化列表更好的方法。 I thought I could use variadic templates for this, so I tried the following:我以为我可以为此使用可变参数模板,所以我尝试了以下操作:
template <template <class> class, class...>
struct type_map;
template <template <class> class BaseT, class... Ts>
struct type_map<BaseT, std::tuple<Ts...>> {
using type = std::tuple<BaseT<Ts>...>;
};
typedef std::tuple<T0, T1, T2> MyTypes;
And in the CPP file:在 CPP 文件中:
template class type_map<Impl, MyTypes>;
However, this didn't instantiate the templates as I intended (the linker complained about the missing symbols).但是,这并没有按照我的意图实例化模板(链接器抱怨缺少符号)。
Is there a way to make this approach work (ie instantiate the template without instantiating an object of it) or a totally different approach that could solve my problem in this situation?有没有办法使这种方法起作用(即实例化模板而不实例化它的对象)或完全不同的方法可以解决我在这种情况下的问题?
I don't think you can do this with variadic templates, but you can do it with the preprocessor.我不认为你可以用可变参数模板来做到这一点,但你可以用预处理器来做到这一点。
I see two options.我看到两个选项。 One would be to use Boost.Preprocessor :
一种是使用Boost.Preprocessor :
// Definitions:
#define ARGUMENTS (T0)(T1)(T2)(T3)(Tx)
#define INSTANTIATE(maUnused, maTemplate, maType) \
template class maTemplate<maType>;
// Usage:
BOOST_PP_SEQ_FOR_EACH(INSTANTIATE, Impl, ARGUMENTS)
BOOST_PP_SEQ_FOR_EACH(INSTANTIATE, Impl2, ARGUMENTS)
Another option would be to use the X macro trick:另一种选择是使用X 宏技巧:
x.hpp x.hpp
X(T0)
X(T1)
X(T2)
X(T3)
X(Tx)
#undef X
using_file.cpp using_file.cpp
#define X(maType) template class Impl<maType>;
#include "x.hpp"
#define X(maType) template class Impl2<maType>;
#include "x.hpp"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.