Is it possible to adapt a input parameter to take a pointer instead of a reference?

时间:2016-04-04 16:37:37

标签: c++

I am doing something like:

std::vector<T> Ints;
std::find_if(Ints.begin(),Ints.end(),f);

bool f(T * input)

Is it possible to adapt f so it can be used in by the find template?

2 个答案:

答案 0 :(得分:0)

Use a lambda:

std::find_if(Ints.begin(), Ints.end(), [](const T& t) { return f(&t); });

If you can’t use C++11, you can write a generic adapter using templates:

template <typename T, bool (*predicate)(const T*)>
bool ReferenceToPointer(const T& t) { return predicate(&t); }

std::find_if(Ints.begin(), Ints.end(), ReferenceToPointer<int, f>);

答案 1 :(得分:0)

If you can't use a lambda expression, and you need an ad-hoc wrapper, you can always do the following.

void your_func()
{
  struct hack
  {
    static void pred_wrap (int& i) { pred(&i); }
  };

  std::find_if(Ints.begin(),Ints.end(), hack::pred_wrap);
}

Note that this is more than a bit hackish, and I only offer it for completeness.