I have a vector containing a large number of elements. Now I want to write a small function that counts the number of even or odd elements in a vector. Since performance is a serious issue, I don't want to put an if statement inside a loop. Therefore, I wrote two small functions, such as:
long long countOdd(const std::vector<int>& v)
{
long long count = 0;
const int size = v.size();
for(int i = 0; i < size; ++i)
{
if(v[i] & 1)
{
++count;
}
}
return count;
}
long long countEven(const std::vector<int>& v)
{
long long count = 0;
const int size = v.size();
for(int i = 0; i < size; ++i)
{
if(0 == (v[i] & 1))
{
++count;
}
}
return count;
}
My question is: can I get the same result by writing one template function as follows:
template <bool countEven>
long long countTemplate(const std::vector<int>& v1)
{
long long count = 0;
const int size = v1.size();
for(int i = 0; i < size; ++i)
{
if(countEven)
{
if(v1[i] & 1)
{
++count;
}
}
else if(0 == (v1[i] & 1))
{
++count;
}
}
return count;
}
And using it like this:
int main()
{
if(somecondition)
{
countTemplate<true>(vec);
}
else
{
countTemplate<false>(vec);
}
}
Will the code generated for the template and version without the template be the same? or will some additional instructions appear?
Please note that counting numbers is just for illustration, so please do not suggest other methods for counting.
:
. , . , , .