You could use variadic templates:
template <typename T, typename ...Args>
void methodAHelper(T && t, Args &&... args)
{
methodB(t, f(t));
methodAHelper(std::forward<Args>(args)...);
}
void methodAHelper() { }
template <typename ...Args>
void methodA(Args &&... args)
{
// some code
methodAHelper(std::forward<Args>(args)...);
// some other code
}
You can possibly get rid of the &&
and the forwarding if you know that your methodB
call doesn t know about rvalue references, that would make the code a bit simpler (you d have const Args &...
instead), for example:
methodAHelper(const T & t, const Args &... args)
{
methodB(t, f(t));
methodAHelper(args...);
}
You might also consider changing methodB
: Since the second argument is a function of the first argument, you might be able to only pass the first argument and perform the call to f()
inside the methodB()
. That reduces coupling and interdependence; for example, the entire declaration of f
would only need to be known to the implementation of methodB
. But that s depends on your actual situation.
或者,如果只有one超载methodB
第一个论点是<代码>T,然后由您通过<代码>std:vector<T> to methodA
,并随附:
void methodA(const std::vector<T> & v)
{
// some code
for (auto it = v.cbegin(), end = v.cend(); it != end; ++it)
methodB(*it, f(*it));
// some more code
}
int main() { methodA(std::vector<int>{1,2,3,4}); }