tags:

views:

140

answers:

4

I tried without any result. My code looks like this:

#include "stdafx.h"
#include <iostream>

#define R() ( rand() )
#define H(a,b) ( a ## b )
#define S(a) ( # a )
#define CAT() H(S(distinct_name_), R())


int main(int argc, _TCHAR* argv[])
{
    std::cout << CAT() << std::endl; 
    std::cout << CAT() << std::endl;
    std::cout << CAT() << std::endl;
    return 0;
}

I would like to get a result like this:

distinct_name_12233
distinct_name_147
distinct_name_435

as a result of concatenating 
distinct_name_ (##) rand()

Right now I am getting an error: term does not evaluate to a function taking 1 arguments. Is this achievable ??

EDIT: I finally succeeded after couple of hours. The preprocessor still does strange things I cannot understand completely. Here it goes:

#include "stdafx.h"
#include <iostream>

class profiler 
{
public:
    void show()  
    {
     std::cout << "distinct_instance" << std::endl;   
    }
};

#define XX __LINE__
#define H(a,b) ( a ## b )
#define CAT(r) H(distinct_name_, r)
#define GET_DISTINCT() CAT(XX)
#define PROFILE() \
    profiler GET_DISTINCT() ;\
    GET_DISTINCT().show() ; \


int main(int argc, _TCHAR* argv[])
{

    PROFILE()
    PROFILE()
    return 0;
}

And the output is:

distinct_instance
distinct_instance

Thanks @Kinopiko for __LINE__ hint. :)

+6  A: 

No, you can't do that. Macros are a compile-time thing and functions are called only at run time, so there's no way you could get a random number from rand() into your macro expansion.

jk
+1 Very much this.
Stephen Canon
+1  A: 

What you are actually getting is...

std::cout << distinct_name_rand() << std::endl;

distinct_name_rand() isn't a function, so it fails with a compile error.

Macros don't execute functions during compile time.

rikh
A: 

You must pass run-time computed value to the macro since macro are evaluated at compile-time. Try:

#define H(a,b) ( a ## b )
#define S(a) ( # a )
#define CAT(r) H(S(distinct_name_), r)

std::cout << CAT(rand()) << std::endl;
Patrice Bernassola
+3  A: 

I see that a lot of people have already correctly answered this question, but as an alternative suggestion, if your preprocessor implements __TIME__ or __LINE__ you could get a result quite like what you want, with a line number or time concatenated, rather than a random number.

Kinopiko