#include <iostream>
#include <vector>
usingnamespace std;
template<typename T>
class Less_thane {
const T val;
public:
Less_thane(const T& v) : val(v) {
cout << "Made a new " << v << endl;
}
booloperator ()(const T& x) const { return x < val; }
};
template<typename C, typename P>
int myCount(const C& c, P pred) {
int cnt = 0;
for (constauto& x : c)
if (pred(x))
cnt++;
return cnt;
}
int main()
{
vector<int> vi{ 1, 2, 4, 5, 6, 7, 8 };
cout << "number of valuse less than 5 = " << myCount(vi, Less_thane<int>(5)) << endl;
cin.get();
return 0;
}
$ g++ -std=c++17 foo.cpp
$ ./a.out
Made a new 5
number of valuse less than 5 = 3
And did you really save anything by omitting to post code with the two include files edited out "for brevity"?
So seemingly only one time a temporarily Less_thane object is created not for each item of the vector. But where exactly will that object be created in the code?
> int myCount(const C& c, P pred)
Well considering that your 'P' is a pass-by-value thing, the temporary will likely be constructed in the stack frame that main creates to call myCount.
You could always add similar debug cout statements for your default ctor, your dtor and maybe even your copy-ctor(s).
But remember, C++ compilers optimise aggressively, so what might seem obvious and apparent in this simple example might not hold true for all cases of Less_thane, and even less so across all compilers.
> Yes, I omitted the two lines for briefness.
And in doing so, you turned an easy copy/paste/compile into something that becomes annoying enough for people to ignore.