2

I have code that looks like

template<typename C>
void invoke() {
  if (thing_known_at_runtime) {
    C::template run<int>(4);
  } else {
    C::template run<char>('a');
  }
}

struct output {
  template<typename T>
  static void run(T x) {
    cout << x;
  }
};

invoke<output>();

And it works.

But I don't like the heavyweight definition of output. I'd like to be able to write:

template<typename T>
void output(T x) {
  cout << x;
}

And then call either invoke<output>() or invoke(output). Is there a way to define invoke so that this works?

(Both output and invoke are more complicated -- this is a simplified version for asking the question with. No, solutions that involve knowing int when I call invoke are not helpful.)

dspeyer
  • 2,904
  • 1
  • 18
  • 24
  • 2
    Is C++11 allowed? And am I understanding correctly that you just want to call a function with stored arguments? – chris Apr 02 '13 at 06:57
  • How can std::function help me? Yes, C++11 is allowed. I want to call a function with stored (actually calculated) arguments *and template parameters*. In fact, let me edit the example to make that clear. – dspeyer Apr 02 '13 at 07:00
  • Are you not willing to define two versions of `invoke()`? – jxh Apr 02 '13 at 07:05
  • 1
    That won't work smoothly, as functions can only be passed via a function pointer, which needs a concrete type at the point of passing (i.e., you can't supply the template parameter later on). – Xeo Apr 02 '13 at 07:18

1 Answers1

0

You cannot do such thing. You should knowns, what you want to do, BEFORE call to invoke. Something like this will work well

void invoke(const std::function<void()>& func)
{
   func();
}

template<typename T>
void output (const T& val)
{
   std::cout << val << std::endl;
}

if (rand() % 2)
{
   invoke(std::bind<void(&)(const int&)>(&output, globals::value_calculated));
}
else
{
   invoke(std::bind<void(&)(const char&)>(&output, globals::value));
}

Full example on lws: http://liveworkspace.org/code/1uLIr4$0

ForEveR
  • 55,233
  • 2
  • 119
  • 133