可变参数函数周围的 C++ 向量包装器 [英] C++ Vector wrapper around variadic function

查看:37
本文介绍了可变参数函数周围的 C++ 向量包装器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的 API:

I have an api that looks like this:

template<typename... Args>
Widget::Widget(std::string format_str, Args&&... args);

如果你有一个 'args' 的字符串向量,即在编译时不知道 args 的长度,你会如何调用这个方法?

How would you call this method if you have a vector of strings for 'args', i.e. the args length isn't known at compile time?

包装函数的实现是什么样的,将它转换成这样的东西?

What would the implementation of a wrapper function look like that would convert this to something like this?

template<typename... Args>
Widget::WrapperWidget(std::string format_str, vector<string>);

推荐答案

以下内容可能会有所帮助:

Following may help:

#if 1 // Not in C++11
#include <cstdint>

template <std::size_t ...> struct index_sequence {};

template <std::size_t I, std::size_t ...Is>
struct make_index_sequence : make_index_sequence < I - 1, I - 1, Is... > {};

template <std::size_t ... Is>
struct make_index_sequence<0, Is...> : index_sequence<Is...> {};

#endif // make_index_sequence

// you may use `std::tostring`
template <typename T> std::string myToString(T&& t);

class Widget
{
public:
    Widget(std::string format_str, const std::vector<std::string>& v);

    // this will call Widget(std::string, const std::vector<std::string>&)
    template<typename... Args>
    explicit Widget(std::string format_str, Args&&... args) :
        Widget(format_str, std::vector<std::string>{myToString(std::forward<Args>(args))...})
    {}


    // This will call Widget(format_str, a[0], a[1], .., a[N - 1]) // So the Args&&... version
    template <std::size_t N>
    Widget(std::string format_str, const std::array<std::string, N>& a) :
        Widget(format_str, a, make_index_sequence<N>())
    {}

private:
    template <std::size_t N, std::size_t...Is>
    Widget(std::string format_str, const std::array<std::string, N>& a, const index_sequence<Is...>&) :
        Widget(format_str, a[Is]...)
    {}

};

这篇关于可变参数函数周围的 C++ 向量包装器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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