variadic模板的variadic变量初始化
Variadic variable initialization for variadic template
我有一个模板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_;
};
相关文章:
- 是否可以初始化不可复制类型的成员变量(或基类)
- C++使用整数的压缩数组初始化对象
- C++初始化基类
- 多成员Constexpr结构初始化
- 复制列表初始化的隐式转换的等级是多少
- 内联映射初始化的动态atexit析构函数崩溃
- 如何在C++中初始化嵌套类中的2个memeber
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 没有用于初始化C++中的变量模板的匹配构造函数
- 在未初始化映射的情况下,将值插入到映射的映射中
- C++成员初始化
- 为什么在C++中首先初始化成员类
- 同时具有"聚合初始化"和"模板推导"
- 初始化具有非默认构造函数的std::数组项的更好方法
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 在C和C++中初始化结构中的数组
- 标准是否使用多余的大括号(例如 T{{{10}}})定义列表初始化?
- variadic模板的variadic变量初始化
- C++11使variadic构造函数了解一个初始化列表的初始化列表