amigo421
amigo421

Reputation: 2541

expansion parameters pack (values) from template arguments

there is a trying to expand the pack using usual way with recursion:

template<bool first> int func1(int value = 0) {
    return some_func(first, value);
}

template<bool first, bool... args> int func1(int value = 0) {
    return func1<args...>(some_func(first, value) );
}

at the last step of compile time recursion, the call of func1 is ambiguous, first candidate is a first function , it's clear , some concrete specialization in my case:

int func1(int) [with bool first = false]

but second one is

int func1(int) [with bool first = false; bool ...args = {}]

you see that is also correct - empty set of the arguments after first one. any idea to prevent this ?

thank you

Upvotes: 2

Views: 122

Answers (2)

amigo421
amigo421

Reputation: 2541

so the finally, I didn't use the recursion, but the only code below.

(actually std::array is not required but more useful from my perspective , the expanding can be archived by using C-like array too)

template <bool... args> unsigned long func1() {
    std::array<bool, sizeof...(args)> ar{args...};

    // the piece specific for my task
    std::bitset<sizeof...(args)> bs;
    for(std::size_t i = 0; i < ar.size(); ++i) {
        bs[i] = ar[i];
    }

   // ... processing ... 
    return bs.to_ulong();
}

Upvotes: 0

Vittorio Romeo
Vittorio Romeo

Reputation: 93264

Disambiguate the base case from the recursive case by adding an explicit second parameter:

template<bool first> int func1(int value = 0) {
    return some_func(first, value);
}

template<bool first, bool second, bool... args> int func1(int value = 0) {
    return func1<second, args...>(some_func(first, value) );
}

Wandbox example

Upvotes: 5

Related Questions