jeudi 20 avril 2017

How can I mark a function with an attribute conditionally on the value of a parameter?

My concrete use case is marking a function [[noreturn]] conditionally on the function’s first parameter being a specific known value.

void log_error(const severity sev /* other parameters here */)
    [[attr_if(sev == severity_fatal, noreturn)]]
{ /* function body here */ }

(I've invented the attr_if syntax vaguely based on Rust's cfg_attr; I don't care if the solution looks even remotely like this as long as the call sites of log_error can stay the same.)

I don't need the attribute to apply when sev is only knowable at runtime, even if it might be severity_fatal; I only need the noreturn attribute to be present if it's knowable at compile time that sev is exactly severity_fatal statically. I'm using Clang and can rely on any extensions present in 3.8 and earlier if necessary, but a truly compiler-agnostic solution would be ideal.

Aucun commentaire:

Enregistrer un commentaire