1

I would like to do something to the following effect:

template <class A>
A doThings(A input) { /* do something */ }

void doTwoThings(ClassB inputB, ClassC inputC, template <class A> A(A) func) // This syntax is wrong but how to achieve this effect?
{
  std::cout << func<ClassB>(inputB);
  std::cout << func<ClassC>(inputC);
}

doTwoThings(5, "testStr", doThings);

Basically, I am trying to pass a function template as an argument to a normal function, and within that function, specialise the function template into two or more overloads and use them. Is there a way to do that in C++?

1 Answers1

2

Not sure if it match your need, but you might do

template <typename F>
void doTwoThings(ClassB inputB, ClassC inputC, F func)
{
  std::cout << func(inputB);
  std::cout << func(inputC);
}

doTwoThings(5, "testStr", [](const auto& input){ doThings(input); });
Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • This achieves exactly what I wanted to do. However I wonder if there is a way to do this in C++11? Because auto& for lambda argument is only available from c++14 onwards. – RelativisticPenguin Jan 12 '22 at 15:42
  • 2
    You can still create an *"old"* functor: `struct ThingDoer { template void operator()(const T& input )const { doThings(input); } };` and `oTwoThings(5, "testStr", ThingDoer{});` – Jarod42 Jan 12 '22 at 15:46