2017-08-09 44 views
2

我正在使用我的C99代碼中P99中定義的P99_FOR宏來遍歷VA_ARGS。它完美的作品。C++中的P99_FOR 11

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; 
+0

你在尋找類似[這(在va_arg-DOC)](http://en.cppreference.com/ W/CPP /實用/可變參數/在va_arg)?或者你正在尋找這個更簡單的版本? – TobiMcNamobi

+0

我已經知道va-arg了。我不想使用任何功能。 – ManiAm

+0

請向我們展示一些[示例代碼](https://stackoverflow.com/help/mcve)。 – TobiMcNamobi

回答

2

你有一對夫婦的路要走。如果您可以獲取數據的迭代器,則可以使用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>()); 

    [...] 
} 

如果你的論點是不iterateable,例如棧單變量,你必須建立它自己的,使用variardic模板:

#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; 
}