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:template class Impl<T0>;template class Impl<T1>;template class Impl<T2>;...template class Impl<Tx>;随着 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. 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;在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 (i.e. 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.我看到两个选择.一种方法是使用 Boost.Preprocessor :I see two options. One would be to use 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)另一种选择是使用 X宏技巧:Another option would be to use the X macro trick: x.hppX(T0)X(T1)X(T2)X(T3)X(Tx)#undef X using_file.cpp#define X(maType) template class Impl<maType>;#include "x.hpp"#define X(maType) template class Impl2<maType>;#include "x.hpp" 这篇关于使用可变参数模板的显式模板实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-21 18:37