Variadic template expansion

Hi, I'm playing with variadic templates and as a simple test I would like to be able to sum various offets into an array. Here is the code:

1
2
3
4
5
6
7
template< int...N >
uint8_t paramTest( uint8_t * args )
{
    uint8_t t = sizeof...(N);
    t += args[N...];
    return t;
}


with a call of something like:

1
2
uint8_t p[5];
paramTest<5,4,7>( p );


However this raises a compilation error of:

expected ‘]’ before ‘...’ token

So I was wondering what the correct way to do this is.
Last edited on
Hi,

Does this help? Particularly the examples at the end.

http://en.cppreference.com/w/cpp/language/parameter_pack


I don't have any experience with this, just chucking it out there :+)
Templates aren't my forte, but I don't think that's how it works.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//http://ideone.com/o8bKRZ
#include <iostream>
#include <iterator>
#include <string>

template <typename T>
T paramTest(const T* arr, std::size_t index)
{
    return arr[index];
}

template<typename T, typename... Args>
T paramTest(const T* arr, std::size_t index, Args... args)
{
    return arr[index] + paramTest(arr, args...);
}

int main()
{
    int p[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    int sum = paramTest(p, 5, 4, 7);
    std::cout << sum;

}


Useful link: http://eli.thegreenplace.net/2014/variadic-templates-in-c/

[Edit: Although, I think I would prefer the following solution]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// http://ideone.com/JXkPrY
#include <initializer_list>
#include <iostream>
#include <iterator>
#include <numeric>
#include <string>

template <typename T>
T add_select(const T* arr, std::initializer_list<std::size_t> selection)
{
    using std::begin; using std::end;
    return std::accumulate(begin(selection), end(selection), T(), [=](T a, std::size_t b) { return a + arr[b]; });
}

int main()
{
    int p[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    int sum = add_select(p, { 5, 4, 7 });
    std::cout << sum << '\n';

    std::string s[9] = { "abc", "def", "ghi", "jkl", "mno", "pqr", "stu", "vwx", "yz" };
    std::string result = add_select(s, { 2, 4, 6 });
    std::cout << result << '\n';
}
Last edited on
Topic archived. No new replies allowed.