【问题标题】:P99_FOR in C++11C++11 中的 P99_FOR
【发布时间】:2017-08-09 06:27:46
【问题描述】:

我在 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;

【问题讨论】:

  • 您在寻找类似this (va_arg-doc) 的东西吗?还是您正在寻找更简单的版本?
  • 我已经知道 va-arg。我不想使用任何功能。
  • 请给我们看一些sample code
  • 也许您想使用更现代的技术(模板、lambdas)编写自己的P99_FOR 版本。如果您提供代码示例,也许 SO 社区可以帮助您。

标签: c++ p99


【解决方案1】:

你有几种方法可以走。如果您可以获取数据的迭代器,则可以使用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;
}

【讨论】:

    猜你喜欢
    • 2012-12-04
    • 1970-01-01
    • 2012-04-11
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-20
    • 1970-01-01
    相关资源
    最近更新 更多