如何迭代元组(使用C++ 11)?我尝试了以下方法:
for(int i=0; i<std::tuple_size<T...>::value; ++i)
std::get<i>(my_tuple).do_sth();
Run Code Online (Sandbox Code Playgroud)
但这不起作用:
错误1:抱歉,未实现:无法将"Listener ..."扩展为固定长度的参数列表.
错误2:我不能出现在常量表达式中.
那么,我如何正确迭代元组的元素?
我在元组中有一些值,我希望在元素方面添加另一个元组.所以我想要这样的功能:
std::tuple<int,int> a = {1,2};
std::tuple<int,int> b = {2,4};
std::tuple<int,int> c = a + b; // possible syntax 1
a += b; // possible syntax 2
a += {2,4}; // possible syntax 3
Run Code Online (Sandbox Code Playgroud)
输出元组将具有该值的位置 {3,6}
I have an overloaded function that I have to call with many different types. The simple approach is:
uint8_t a;
uint16_t b;
//....
double x;
doSomething(a);
doSomething(b);
//...
doSomething(x);
Run Code Online (Sandbox Code Playgroud)
expressing those calls succinctly can be done with a variadic template as explained at this Q&A. The code will look somewhat like this:
auto doSomethingForAllTypes = [](auto&&... args) {
(doSomething(args), ...);
};
uint8_t a;
uint16_t b;
//....
double x;
doSomethingForAllTypes(a, b, ... ,x);
Run Code Online (Sandbox Code Playgroud)
But I'll have to do this at …
我是元编程的新手.我看过其他类似的问题,但没有一个问题符合我的要求.
这是我尝试反转std :: tuple.我的主要问题是反转输入元组中的数据.
反转指数的逻辑不合适,我无法从这个阶段开始.
到目前为止的代码:
//===========================================================!
// type inversion of a tuple
template < typename Tuple, typename T >
struct tuple_push;
template < typename T, typename ... Args >
struct tuple_push<std::tuple<Args...>, T>
{
typedef std::tuple<Args..., T> type;
};
template < typename Tuple >
struct tuple_reverse;
template < typename T, typename ... Args >
struct tuple_reverse<std::tuple<T, Args...>>
{
typedef typename tuple_push<typename tuple_reverse<std::tuple<Args...>>::type, T>::type type;
};
template < >
struct tuple_reverse<std::tuple<>>
{
typedef std::tuple<> type;
};
//===========================================================!
template <typename First, typename …Run Code Online (Sandbox Code Playgroud) 是否可以编写可变参数模板类
template<typename Functor, int... D>
struct Foo
{
void bar()
{
// ???
}
};
Run Code Online (Sandbox Code Playgroud)
这相当于
template<typename Functor, int D0>
struct Foo<Functor, D0>
{
void bar()
{
Functor f;
double d0[D0];
f(d0);
}
};
template<typename Functor, int D0, int D1>
struct Foo<Functor, D0, D1>
{
void bar()
{
Functor f;
double d0[D0];
double d1[D1];
f(d0, d1);
}
};
// And so on...
Run Code Online (Sandbox Code Playgroud)
也就是说,传递给仿函数的参数数量等于模板参数的数量.参数应该在堆栈上分配.