Reputation: 1145
Is it possible in C++ to create variable, which will be expanded after each time it used to different value?
For example, I want that following
#define mytype [smth here]
void foo(mytype a,mytype b,mytype c)
will be expanded into
void foo(mytype1 a,mytype2 b,mytype3 c)
or
void foo(mytype1 a,mytype11 b,mytype111 c)
Upvotes: 1
Views: 300
Reputation: 1
#define mytype [smth here]
#define TYPE(a, b) _TYPE(a, b)
#define _TYPE(a, b) a##b
void foo(TYPE(mytype, 1) a, TYPE(mytype, 2) b, TYPE(mytype, 3) c)
Upvotes: -1
Reputation: 171097
Here is an example of using Boost.Preprocessor to achieve the function parameter thing:
#include <boost/preprocessor/repetition/enum_binary_params.hpp>
void foo(BOOST_PP_ENUM_BINARY_PARAMS(3, mytype, p));
That will expand to
void foo(mytype0 p0, mytype1 p1, mytype2 p2);
Upvotes: 3
Reputation: 11513
If it should only increase when outputting, you can define a struct overriding the operator<<
, e.g.:
struct myvarstruct {
int i;
myvarstruct() : i(1){}
} myvar;
ostream &operator << (ostream &o, myvarstruct &s) {
return o << "myvar" << s.i++;
}
Upvotes: 0
Reputation: 258548
You can't have a macro that changes what it expands to, but you can make what it expands to mean different things:
std::string foo()
{
static int x;
return std::string("myvar") + std::to_string(x++) + "\n";
}
#define myvar foo()
and
cout<<myvar;
cout<<myvar;
will print out
myvar1
myvar2
Upvotes: 1