If I define a macro:
Code://Can i do something *like* this?
#define doSmth( <int>val ) {...elided...}
Printable View
If I define a macro:
Code://Can i do something *like* this?
#define doSmth( <int>val ) {...elided...}
macro is processed by preprocessor that has no idea about types. So what do you think will be answer to your question?
Right, but isn't it really just adding code to your code and THEN compiling? Can't a compiler put in that code and then try compiling? (I guess not, just hopeful)
I say this because when I define a macro that has in it a "dynamic_cast" call and then pass an object that has no virtual functions and is not of the proper type, the compiler alerts me and says that's an error. So I thought maybe it could do the checking during compile...
Code:#define doSmth( obj )
{ \
SomeClass* c; \
c = dynamic_cast<SomeClass*> obj; \
...elided... \
}
int main()
{
int i;
//compiler knows enough to complain about the dynamic cast attempt on "i"
doSmth( i );
}
I usually like to follow the personal rule of "If I can't help don't post", but sometimes my curiosity gets me.
Why are you wanting to do something like this if I may ask?
What would be the benefit over something like:
Code:void doSmth(int val) {
// rawr, inline me?
}
Compiling is done by compiler - it works with the output of the preprocessor. At this step no sign of macro is anywhere in a sight...Quote:
Right, but isn't it really just adding code to your code and THEN compiling?
preprocessor just replaces some character sequencies in your code with other character sequencies...
Basically, if you want to know about types, don't use macros. You can use inline functions or something instead. Then you can overload the functions to deal with different types. For example:
If you wanted more generic functions you could use templates as well. For example:Code:inline void print(int x) {
std::cout << x << std::endl;
}
inline void print(const char *str) {
std::cout << '"' << str << '"' << std::endl;
}
It all depends on what you're trying to do . . . .Code:template <typename type>
inline void print_address(type x) {
std::cout << &x << std::endl;
}
template <typename type>
inline void print_address(type *x) {
std::cout << x << std::endl;
}
[edit] To expand on what the others said about macros:
When you use code like
the preprocessor takes that and generates this:Code:#define N 10
int x = N;
The compiler only sees this modified version. It cannot know about #defines, which is why compiler errors from #defines can be weird. [/edit]Code:int x = 10;