The problem with the template

Why can I do this:

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

void myfunction (int i) {
  cout << " " << i;
}

int main () {
  vector<int> myvector;
  myvector.push_back(10);
  myvector.push_back(20);
  myvector.push_back(30);

  cout << "myvector contains:";
  for_each (myvector.begin(), myvector.end(), myfunction);//<-------See below
return 0;
}

but cannot do this:

template<class T>
    void myfunction (T i) {
          cout << " " << i;
        }

I suspect that it has something to do with args deduction, but it is so enraging that the “regular” fnc is accepted, but the pattern is not.

+3
source share
3 answers

The problem is that you cannot create a pointer to a template function. However, you should be able to create a pointer to an instance function of the template. I have not tried this, but the following should work:

for_each (myvector.begin(), myvector.end(), myfunction<int>)
+10
source

for_each. , operator()(). , :

 std::for_each(myvector.begin(), myvector.end(), &myfunction<int>);

using namespace std, , . , &, , .

+5

. , :

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

template <typename T>
void myfunction (T i)
{
    cout << " " << i;
}

int main () {
  vector<int> myvector;
  myvector.push_back(10);
  myvector.push_back(20);
  myvector.push_back(30);

  cout << "myvector contains:";
  for_each (myvector.begin(), myvector.end(), myfunction<int>);
  cout << endl;
}

:

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

struct MyPredicate {
    template <typename T>
    void operator () (T i)
    {
        cout << " " << i;
    }
};

int main () {
  vector<int> myvector;
  myvector.push_back(10);
  myvector.push_back(20);
  myvector.push_back(30);

  cout << "myvector contains:";
  for_each (myvector.begin(), myvector.end(), MyPredicate ());
  cout << endl;
}
+4

Source: https://habr.com/ru/post/1765619/


All Articles