P99_FOR in C++11
P99_FOR in C++11
我正在使用 C99 代码中 P99 中定义的P99_FOR宏来迭代VA_ARGS。它工作得很好。
P99_FOR(NAME, N, OP, FUNC,...)
现在我想迁移到 C++11,我想知道是否有任何类似于P99_FOR的宏。
这是我在 C99 中的代码:
#ifndef __cplusplus
#include "p99/p99.h"
#undef P00_VASSIGN
#define P00_VASSIGN(NAME, X, I) NAME[I] = X
#define FOREACH(x, y, z, u, ...) P99_FOR(x, y, z, u, __VA_ARGS__);
#else
#define FOREACH(x, y, z, u, ...) ??? // C++ equivalent
#endif
#define set_OCTET_STRING(type, numParams, ...) {
FOREACH(type, numParams, P00_SEP, P00_VASSIGN, __VA_ARGS__);
}
例如,set_OCTET_STRING(myVar->speed, 3, 34, 10, 11)
将扩展到:
myVar->speed[0] = 34; myVar->speed[1] = 10; myVar->speed[2] = 11;
你有几个方法要走。如果可以获取数据的迭代器,则可以使用std::accumulate
。
该示例取自文档:
#include <iostream>
#include <vector>
#include <numeric>
#include <string>
#include <functional>
int main()
{
std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int sum = std::accumulate(v.begin(), v.end(), 0);
int product = std::accumulate(v.begin(), v.end(), 1, std::multiplies<int>());
[...]
}
如果你的参数不可迭代,例如堆栈上的单个变量,你必须使用可变模板自己构建它:
#include <vector>
#include <numeric>
#include <functional>
#include <iostream>
template <class Func, class ReturnType, class... Args>
ReturnType P99_FOR(Func op, ReturnType initialValue, Args... args) {
std::vector<ReturnType> values{args...};
return std::accumulate(values.begin(), values.end(), initialValue, op);
}
template <class... Tags>
struct TagList {};
int main(int argc, char* argv[])
{
int a = 4, b = 10, c = 21;
// You can use predefined binary functions, that come in the <functional> header
std::cout << "Sum:" << P99_FOR(std::plus<int>(), 0, a, b, c) << std::endl;
std::cout << "Product:" << P99_FOR(std::multiplies<int>(), 1, a, b, c) << std::endl;
// You can also define your own operation inplace with lambdas
std::cout << "Lambda Sum:" << P99_FOR([](int left, int right){ return left + right;}, 0, a, b, c) << std::endl;
return 0;
}
相关文章:
- P99_FOR in C++11
- 明确定义'static const variable in a struct'对C++ 11 及以上有什么影响吗?
- OSAtomicAdd32 variant in C++11
- std::nearbyint vs std::round in C++11
- Parsing int in C++11 - stoi
- char16_t and char32_t types in C++11
- 如果不使用C++11,安东尼威廉的"C++ Concurrency in action"是一本合适的书吗?
- 用于循环原因的新 C++11:"error: ‘begin’ was not declared in this scope"
- SIGSEGV(signal 11) 'segmentation fault' in FCTRL2 codechef
- C++11 in QtCreator 3.5.0 on ubuntu
- Using Partial Specialization in C++11
- C++ 11 in vxworks
- hash_value function in C++11
- Efficient Argmin in C++11
- boost::thread_group in C++11?
- C++11 "In class initialization"功能不适用于工会
- C++11 thread_pool, futures, promises support in gcc
- Unicode in C++11
- 使用 C+11 和 Newlib 时出现错误"sigemptyset was not declared in this scope"
- 在索引和值"for i, v in enumerate(listVar):"上是否有 C++/C++11 类似于 python 迭代?