首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >P99_FOR in C++11

P99_FOR in C++11
EN

Stack Overflow用户
提问于 2017-08-09 06:27:46
回答 1查看 682关注 0票数 3

我在我的代码中使用了P99中定义的P99宏,以便在VA_ARGS上迭代。它工作得很完美。

代码语言:javascript
复制
P99_FOR(NAME, N, OP, FUNC,...)

现在我想迁移到C++11,我想知道是否有类似于P99_FOR的宏。

下面是我在C99中的代码:

代码语言:javascript
复制
#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)将扩展到:

代码语言:javascript
复制
myVar->speed[0] = 34; myVar->speed[1] = 10; myVar->speed[2] = 11;
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-09 07:43:38

你还有几条路要走。如果您可以让迭代器访问您的数据,则可以使用std::accumulate

该示例摘自文档:

代码语言:javascript
复制
#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>());

    [...]
}

如果您的参数是不可迭代的,例如堆栈上的单个变量,则必须使用变量模板自己构建它:

代码语言:javascript
复制
#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;
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45583085

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档