Check if function has an empty body

Viewed 190

Is it possible to check (at compile or runtime) if function or class method has an an empty body?

E.g

void empty_body_function(){}
void non_empty_body_function(){int i;}

int main()
{
    assert(magic(empty_body_function) == true);
    assert(magic(non_empty_body_function) == false);
}

P.S.I define non empty body like that: function/method does have non empty body if and only if it has any code(valid C++ code, for sure) inside {} after preprocessing

P.P.S Answering "why" question: What I'm trying to achieve is to check if particular interface implementation "does nothing". No side effects, no calculations, etc

1 Answers

To the best of my knowledge, there's no way to do that. But C++ metaprogramming is complex and it's hard to say about something that it's impossible.

I'll add - in compile time, for any function that is declared but not defined, it's absolutely impossible. The compiler knows nothing about what the function does except for its parameters and return value.

In runtime, you can try to work with the function's pointer and maybe do things, but I'd imagine that anything in that direction will be very dependant on your compiler/linker configuration.

Also, if this question is for a practical use case - I urge you to think about it again. Checking that the function body is empty a weird thing to do.

Related