Search code examples
c++variadic-templates

Misunderstanding variadic template functions


I am unsure how to achieve a particular effect from a variadic template function I wrote. Below is the function I wrote.

template<typename ... T>
bool multiComparision(const char scope, T ... args) {
    return (scope == (args || ...));
}

It was pointed out to me that this actually performs something different to what I wanted despite not creating any bugs in the larger scope of my code.

multiComparision('a', '1', '2', '3');

=>
   return ('a' == ('1' || '2' || '3'));

I had actually intended the function to return the following

multiComparision('a', '1', '2', '3');

=>
   return ('a' == '1' || 'a' == '2' || 'a' == '3');

How can I achieve the desired effect?


Solution

  • How can I achieve the desired effect?

    Wrap your equality comparison expression in parentheses:

    template<typename ... T>
    bool multiComparision(const char scope, T ... args) {
        return ((scope == args) || ...);
    }
    

    live example on godbolt.org


    C++14 solution:

    template<typename ... T>
    constexpr bool multiComparision(const char scope, T ... args) {
        bool result = false;
        (void) std::initializer_list<int>{ 
            ((result = result || (scope == args)), 0)...
        };   
        return result;
    }
    

    live example on godbolt.org