Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variadic template function with more than two parameters

I have the following example where two parameters t1 and t2 are used.

template<typename T>
bool Compare(T t1, T t2)
{
    return t1 == t2;
}

template<typename T, typename... Args> 
bool Compare(T t1, T t2, Args...  args)
{
    return (t1 == t2) && Compare(args...);
}

int main(void)
{
    Compare(1, 1, "string", "string");
}

Function Compare takes pairs of parameters that are the same type and can be compared. Two pairs are compared then parameter pack is passed recursively until the last two parameters are reached. To stop recursion I use an implementation of Compare function without parameter pack.

I would like add the third argument t3 so function Compare should be like this:

template<typename T>
bool Compare(T t1, T t2, T t3)
{
    return t1 == t2 == t3;
}

template<typename T, typename... Args>
bool Compare(T t1, T t2, T t3, Args... args)
{
    return (t1 == t2 == t3) && Compare(args...);
}

int main(void)
{
    Compare(1, 1, 1, "string", "string", "string");
}

I expect that this function takes three parameters to comparison then next three are processed recursively. When I try to compile this code I obtain the following error:

>xxx\source.cpp(4): error C2446: '==': no conversion from 'const char *' to 'int'
1>  xxx\source.cpp(4): note: There is no context in which this conversion is possible
1>  xxx\source.cpp(10): note: see reference to function template instantiation 'bool Compare<const char*>(T,T,T)' being compiled
1>          with
1>          [
1>              T=const char *
1>          ]
1>  xxx\source.cpp(15): note: see reference to function template instantiation 'bool Compare<int,const char*,const char*,const char*>(T,T,T,const char *,const char *,const char *)' being compiled
1>          with
1>          [
1>              T=int
1>          ]
1>xxx\source.cpp(4): error C2040: '==': 'int' differs in levels of indirection from 'const char *'

How to implement this function to compare the sets of three parameters of the same type?

like image 835
msk Avatar asked Mar 15 '16 08:03

msk


1 Answers

t1 == t2 == t3

That doesn't check if t1, t2 and t3 are all equal, it checks if t1 equals t2, then checks if the resulting bool is equal to t3.

Maybe what you want instead is (assuming reasonable equality operators):

t1 == t2 && t1 == t3

So your code would look like this:

template<typename T>
bool Compare(T t1, T t2, T t3)
{
    return t1 == t2 && t1 == t3;
}

template<typename T, typename... Args>
bool Compare(T t1, T t2, T t3, Args... args)
{
    return t1 == t2 && t1 == t3 && Compare(args...);
}

Note that your test call with string literals does pointer comparison, which may not be what you want.

like image 169
TartanLlama Avatar answered Oct 18 '22 11:10

TartanLlama