0

Suppose, I have built an unique function body from below code:

#define TOKENPASTE(x, y) x ## y
#define TOKENPASTE2(x, y) TOKENPASTE(x, y)
#define UNIQUE static void TOKENPASTE2(Unique_, __LINE__)(void)

How can I call this function ?

Macro definition taken from: Creating C macro with ## and __LINE__ (token concatenation with positioning macro).

Community
  • 1
  • 1
Chethan
  • 905
  • 1
  • 10
  • 18
  • In your edited question.. where you want to call the function ? You can describe more. (Because, you can simply call the function as `Unique_1, Unique_2,...`, if they exist at that line) – iammilind Jul 02 '11 at 15:36
  • My question is, if a unique function is attempted to defined, but cannot be called, whats the point? @iammilind, how can you call a function in global scope? – Chethan Jul 07 '11 at 15:25
  • It's correct that you cannot call it so easily. However, you can see my answer, with the help of `template` you have some control to call them. – iammilind Jul 07 '11 at 15:26

2 Answers2

1

No. You cannot. Because you cannot determine a function name at runtime. (i.e. either to call Unique_22 or Unique_44. However you can definitely call Unique<22> or Unique<44>)

So you can use template solution instead. Declare Unique as below:

template<unsigned int LINE> void Unique ();

And #define the macro like this:

#define UNIQUE template<> Unique<__LINE__>() {}

I advice to use __COUNTER__ instead of __LINE__ if your compiler supports it. [Note: which means that in any line you can call the UNIQUE only once and also the macro should be expanded in global or namespace scope (not inside a method).]

iammilind
  • 68,093
  • 33
  • 169
  • 336
  • The answer to the linked question shows that you can do this with the preprocessor. (http://stackoverflow.com/questions/1597007) – Mike Seymour Jul 02 '11 at 09:20
  • The edit doesn't seem to make sense; you can't determine a template argument at runtime either (although it could be a compile-time constant; that seems to be the only advantage your version has over the preprocessor version, but I don't see how it's useful to do that). – Mike Seymour Jul 02 '11 at 09:33
  • @Mike, it may sound vague, but here is what I meant: Suppose at `N`th line, user wants to call the `Unique_N/2` then he cannot call such function using macro solution (i.e. at line `10`, user wants to call `Unique_5`). But with `template` solution one can call as `Unique()`. – iammilind Jul 02 '11 at 09:37
0

After replacing the code with the one given in the answer to the SO question you pointed so that it works, ... you can't call this function directly since you can't know for sure its name, that will change if the code change. I have no clue about how this can be useful in code (maybe scanning an object for symbol like Unique_[0-9]+? Anyway, it would be an indirect use, in code, as said, you can't use it reliably.

ShinTakezou
  • 9,432
  • 1
  • 29
  • 39