variadic模板的variadic变量初始化

Variadic variable initialization for variadic template

本文关键字:variadic 初始化 变量      更新时间:2023-10-16

我有一个模板A类A,我想从另一个类B

调用模板函数

标题看起来像:

template<typename... T> class A
{
public:
    A();
    void get(type_X params);
private:
    B b_;
};

和.hxx:

template<typename... T> void A<T...>::get(type_X params)
{
    /*here lies my problem*/
    T... variable; // just like we would do string s;
                   // and pass it to a function f(string& s) to assign it
    b_.get(params, variable...);
    /* do something with updated value of variable */
}

成员B_(B类)具有模板功能,看起来像

template<typename... T> int B<T...>::get(type_X params, const T&... variable)
{
    /* change variable, just like we would assign a new value to a string& */
    return 0; 
}

,我不知道如何初始化(如果可能的话)我的" t ..."对象作为参数作为模板函数b :: get。

感谢您的帮助

首先,在编译时间创建一包积分索引的索引机械:

template< std::size_t... Ns >
struct indices {
    typedef indices< Ns..., sizeof...( Ns ) > next;
};
template< std::size_t N >
struct make_indices {
    typedef typename make_indices< N - 1 >::type::next type;
};
template<>
struct make_indices< 0 > {
    typedef indices<> type;
};

现在,您可以创建一个对象数组:

T vars[] = { T()... };

接下来,您需要一个辅助功能来创建一个可以推断整数包装的上下文。这样的东西:

template<typename... T, T, size_t... I>
int helper(type_X params, T* arr, indices<I...>)
{
    return b_.get(params, arr[I]...);
}

对于arr参数,您要传递以前创建的数组vars,并且在最后一个您通过make_indices<sizeof...(T)>::type()

希望会有所帮助。

首先,这是无效的语法:

T... variable;

要做这样的事情,您需要创建一个元组:

std::tuple<T...> variable;

然后,您使用其中一种技术来调用元组成员作为参数:

'解开包装调用匹配功能指针的元组将元组的内容作为变异函数参数如何将元组扩展到variadic模板函数的参数?

以下可能会帮助您:

#if 1 // Not in C++11
// Helper class to be able to use expansion of std::get<Index>(tuple)
template <int... Is> struct index_sequence {};
// Following create index_sequence<0, 1, 2, .., sizeof...(Is) - 1>
template <int Index, int... Is>
struct make_index_sequence { // recursively build a sequence of indices
    typedef typename make_index_sequence<Index - 1, Index -1, Is...>::type type;
};
template <int... Is>
struct make_index_sequence<0, Is...> { // stop the recursion when 0 is reached
    typedef index_sequence<Is...> type;
};
#endif
template<typename... Ts> class A
{
public:
    void get(type_X params)
    {
        std::tuple<Ts...> t;
        a.get(params, t, make_index_sequence<sizeof...(Ts)>());
    }
private:
    template<std::size_t ... Is>
    void get(type_X params, std::tuple<Ts...>& t, index_sequence<Is...>)
    {
        b_.get(params, std::get<Is>(t)...);
    }
private:
    B b_;
};