使用可变参数模板的显式模板实例化 [英] Explicit template instantiation with variadic templates

查看:55
本文介绍了使用可变参数模板的显式模板实例化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个模板类 Impl (带有一些抽象方法),它们部分地在CPP文件中实现,因此我需要显式实例化模板以供链接器找到它,如下所示:

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.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"

这篇关于使用可变参数模板的显式模板实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆