c++ - 使用可变模板的显式模板实例化

标签 c++ templates c++11 variadic-templates

我有几个在 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/

相关文章:

c++ - 确定鼠标指向的对象是什么?

c++ - 尝试在 C++ 中创建实例时“未声明的标识符”

c++ - [Args...] 为空的可变参数模板的部分模板特化

c++ - 借助 static_assert 改进诊断

c++11 - 比较 shared_ptr 实例的有效情况

c++ - 在没有条件/分支的情况下使用逻辑 AND/OR

c++ - 使用模板化方法处理意外行为

javascript - 如何在 Handlebar 模板中找到数组长度?

c++ - 将数组作为参数传递给 std::thread

c++ - 没有用于错误调用的匹配函数。将字符串插入 vector