使用boost::mpl::vector创建可变模板

Using boost::mpl::vector to create variadic templates?

本文关键字:vector boost mpl 使用 创建      更新时间:2023-10-16

我现在一直使用C++03,我想创建一个全局函数,接受任何数量的类型安全参数(如果需要,可以达到合理的限制,比如9)。

我可以访问我的代码库中的完整boost库,所以我希望boost::mpl::vector在这里有用。我也不希望这写起来太不方便。呼叫站点的语法应该很简单,如下所示:

LogDebugMessage("Number of cats and dogs:", m_myPets->NumCats(), m_myPets->NumDogs());

以类型安全的方式实现这一点的最佳方式是什么?

编辑

我也意识到我可以使用模板专门化,但我不想最终定义同一个结构9次,每个额外的模板参数一次。这太乱了。如果可能的话,我想尽量避免。

最好的方法是9个重载P

然而,最简单的方法是boost::tuple,而不是使用boost::mpl,因为mpl大多只在编译时使用。呼叫站点(用户)然后会写一些类似的东西

LogDebugMessage("Number of cats and dogs:",
    boost::tie(m_myPets->NumCats(), m_myPets->NumDogs()));

tie创建一个引用元组。或者,如果通话涉及临时费用:

LogDebugMessage("Number of cats, dogs and birds:",
    boost::make_tuple(m_myPets->NumCats(), m_myPets->NumDogs(), 0));

如果记录的类型有点重(boost::make_tuple进行复制),则可以使用旧的boost::ref

你的LogDebugMessage看起来像这样:

template<class Tuple>
void LogDebugMessage(std::string const& msg, Tuple const& args);

之后,您可以使用类似于我的元组打印机的递归来解压缩元组。请注意,只有operator<<实际使用可变模板,并且这样做只是为了拾取std::tuple。您很可能只使用print_tuple部分。

相关文章: