5

I've been browsing through some of the questions here and I found some sample code that passed (what looks like) an integer casted as type void as the type parameter for a templated object. Here's an example of what I mean:

SomeRandomObject<void(int)> Object;

I would appreciate it if someone could explain the "void(int)" part of the code and what it does.

2 Answers2

7

That type is "function that takes an int and returns void".

Jon
  • 428,835
  • 81
  • 738
  • 806
2

The type is a function type. You may not be so familiar with it, because until now it has only been used in pointer types:

typedef int (ft)(void);  // Huh?  (raw function type)
typedef ft *fp;          // ???   (pointer to function)

typedef int (*fp_oldstyle)(void); // Ahh... (same as fp)

Functions themselves do have types, but since you cannot declare variables of that type or references to it, the only thing you would typically use are pointers, which are declared in the familiar syntax on the last line. For any function int foo(void);, both foo and &foo are interpreted as the pointer, so the "raw" function type ft isn't needed.

However, with the new template magic surrounding std::function, std::bind and lambdas, it is now a much more common thing to see naked function types in template parameters.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • It is possible to have function reference. – Khaled Alshaya Oct 27 '11 at 22:41
  • @AraK: Ah, that's true: ft & f = foo; f();. Thanks! Doesn't seem to be used a lot, though; I suppose on account of references not being reassignable. – Kerrek SB Oct 27 '11 at 23:47
  • I agree, I have seen it rarely. Related question of mine: http://stackoverflow.com/questions/1516958/could-someone-please-explain-the-difference-between-a-reference-and-a-pointer – Khaled Alshaya Oct 27 '11 at 23:47