I'm trying to do something like this:
#define FOO printf("No paren\n");
#define FOO(x) printf(x);
Is there a way to do this with c++ macros?
No. A given macro name can either be plain ("object-like") or "function-like", not both.
I would not advise it, but it is possible with some help from C++ itself,
#include <iostream>
template<typename T>
struct CustomMessage
{
const T& t;
CustomMessage(const T& t) : t(t)
{}
};
struct DefaultMessage
{
template<typename T> CustomMessage<T> operator() (const T& t)
{
return {t};
}
};
template<typename T>
std::ostream& operator<< (std::ostream& os, const CustomMessage<T>& message)
{
return os << message.t;
}
std::ostream& operator<< (std::ostream& os, const DefaultMessage& message)
{
return os << "no paren\n";
}
using namespace std;
#define FOO std::cout << DefaultMessage{}
int main() {
int x = 42;
FOO;
FOO(x);
return 0;
}
Live one Ideone https://ideone.com/VboP8R
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With