我有几个在 CPP 文件中部分实现的模板类 Impl
(带有一些抽象方法),因此我需要显式实例化我的模板以便链接器找到它,如下所示:
template class Impl<T0>;
template class Impl<T1>;
template class Impl<T2>;
...
template class Impl<Tx>;
随着 Tx
类型数量的增加,我想找到一种比在所有必要文件中手动扩展这些显式实例化列表更好的方法。我想我可以为此使用可变参数模板,所以我尝试了以下操作:
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>;
但是,这并没有像我预期的那样实例化模板(链接器提示缺少符号)。
有没有办法使这种方法起作用(即实例化模板而不实例化它的对象)或完全不同的方法可以解决我在这种情况下的问题?
最佳答案
我不认为你可以用可变参数模板来做到这一点,但你可以用预处理器来做到这一点。
我看到两个选项。一种是使用 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 macro技巧:
x.hpp
X(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"
关于c++ - 使用可变模板的显式模板实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23628177/