0

For example, I want something similar in meaning to this:

//Somethere in Windows header
struct COUPLE {
    WORD part0;
    WORD part1;
}

//In my code
#if sizeof(COUPLE) == sizeof(INT)
    #define COUPLE_TO_INT(arg) (*((INT*)((void*)&arg)))
#else
inline INT COUPLE_TO_INT(const COUPLE &arg) {
    return ((INT)arg.part1 << 16) + arg.part0;
}
#endif

Of course, the code from the example is not compiled.

And, of course, I can do with just the INT COUPLE_TO_INT(const COUPLE &arg) function, but as I noticed, in most cases it is not required and I can do with reinterpret_cast, which requires less resources (shifting and summation). However, there may be situations where padding breaks this mechanism, so a backup path is required.

It is clear that I cannot influence the alignment of the structures from the header in any way, but I can find out their size and act on this.

Is it possible to branch a macro based on an C++ assert or something of the same kind?

Alex A.
  • 422
  • 3
  • 12
  • 2
    What about the compiler optimizations? Seems very unlikely it couldn't handle this for you and your efforts here are just wasted. – super Oct 21 '22 at 20:01
  • 1
    You are just opening yourself up to bugs and problems by trying to "optimize". You didn't check enidianness, you didn't parenthesize the macro argument and the macro doesn't work for rvalues. – Passer By Oct 21 '22 at 21:11
  • @super Optimizations are sometimes not an obvious thing. It was such that I expected wit from the compiler, but he did not show it, and vice versa - he did non-obvious things. As far as I am convinced, it is better to set up an experiment in each individual case. – Alex A. Oct 23 '22 at 22:03
  • @PasserBy I wrote the code just for an example. In reality, I will do more checks. I just wanted to clarify if there is a potential for more flexible work with the preprocessor. It turns out that there is no? – Alex A. Oct 23 '22 at 22:06
  • @AlexA. Take some parts of your production code. Compile it with both the function conversion and a reinterpret-cast, then compare the assembly. – super Oct 24 '22 at 08:17

1 Answers1

3

You could use constexpr if in a normal function, e.g.

int coupleToInt(const COUPLE& c) {
    if constexpr (sizeof(COUPLE) == sizeof(int)) {
        // ...
    }
    else {
        // ...
    }
}

This feature is available since C++17 and you tagged the question as such. The condition is evaluated at compile time.

Peter H
  • 475
  • 5
  • 14
  • Yes, I know about that. However, I was wondering if it was possible to work at the macro level, that is, at the preprocessor level. Does it mean. what is the answer "no"? – Alex A. Oct 23 '22 at 22:00