Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to make a macro have different behavior if it has parenthesis?

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?

like image 208
Phylliida Avatar asked Dec 10 '22 18:12

Phylliida


2 Answers

No. A given macro name can either be plain ("object-like") or "function-like", not both.

like image 97
Steve Summit Avatar answered May 19 '23 18:05

Steve Summit


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

like image 22
tahsmith Avatar answered May 19 '23 18:05

tahsmith