使用boost::mpl::vector创建可变模板
Using boost::mpl::vector to create variadic templates?
我现在一直使用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
部分。
相关文章:
- 使输出流式处理运算符适用于 boost::variant<std::vector<int>、int、double 的正确方法是什么>
- boost::container::vector 无法用谷物序列化?
- 如何从 boost::container::vector<std::string>::iterator 访问索引和对象?
- Boost.interprocess Vector 作为类成员
- 在 boost::<double>asio::buffer 中使用像 std::vector<std::complex> 这样的参数
- 将 std::vector<boost::optional<double>> 转换为 std::vector<double>
- 使用 boost::序列化序列化 std::vector of unique_ptr 在 Linux 上失败
- boost::spirit::x3 phrase_parse 在进入 Vector 之前进行算术运算
- 有没有一种优雅的方法可以从 std::vector 实例化 boost::array
- 使用 boost zlib 从 std::vector 中的文件中读取压缩的 zraw 数据
- boost::d ynamic_bitset 与 std::vector 的结果不一致<bool>?
- 如何使用 boost asio 通过 UDP 套接字发送无符号字符的 std::vector?
- Boost::p roperty_tree:在XML解析器中使用std::vector<>在一个键中存储多个值
- Copy std::vector to boost::interprocess::vector
- C++类似于 std::vector / boost::array 的文件内存映射容器
- 为什么我的结构不能有 boost::variant 类型的成员,但可以有 vector<boost::variant> 类型的成员?
- 使用 std::vector<boost::shared_ptr<Base_Class>> 或 boost::p tr_vector 的性能注意事项是什么<Base>
- 如何将 std::vector<boost::shared_ptr<T>> 复制到 std::list<T>
- 使用 std::vector<boost::function> with boost::bind
- 解析为 vector<boost::string_view> 使用 boost::spirit::x3