Question

(Follow-up of Overload ternary ?: operator, or change to if{}else{} in included files.)

Context

Research project here. In my C++ library, I am including C files using #include "aprogram.c" which I execute symbolically by overloading (almost) all operators.

I have to be able to detect (condition) ? this : that and extract condition, this and that for usage in my symbolic execution library, for the following cases:

(a >= 0) ? a : -a
(a >= b) ? a : b

Conceptual question

Because I cannot overload the ternary ?: operator in C++, and it only has to work for the above cases, can't I 'overload' them by using macros somewhat like:

#define TO_NEG(a) ((a >= 0) ? a : -a)
#define MAX(a,b)  ((a >= b) ? a : b)

and implement TO_NEG(a) and MAX(a,b)?

Edit: Clarification

With this, I want to achieve that my library

  1. detects ?: in both cases
  2. converts it to TO_NEG or MAX
  3. uses new code I wrote for TO_NEG and MAX
Was it helpful?

Solution

Assuming your operator >= produces a MyBool type, I think you can get almost there with:

#define ? .ternary(
#define : )||

template <typename T>
T MyBool::ternary(T val) { 
  if (m_isTrue) return val;
  return T(0)
}

Several things to note:

  1. This doesn't work for a>=b if a is 0 and b is negative.
  2. This is a terrible terrible hack that will break on many edge cases.
  3. You can't actually use : as a symbol in a #define, so you'd have to use some other means of replacing them, at which point, you should probably use something like @raxvan's answer

OTHER TIPS

You can define something that will replace the ? operator inside the c source file.

The closest thing you can do is the following:

#define QUESTION_OPERATOR(COND,THIS,THAT) ((COND) ? (THIS) : (THAT))
//here you can do custom validations to all the parts if you want

usage:

(cond) ? (This) : (That) //you need to replace this with:
QUESTION_OPERATOR(cond,This,That)

Yes, you can use the ternary operator in macros, but they must be correctly parenthesized:

#define TO_NEG(a) (a >= 0) ? (a) : -(a)
#define MAX(a,b)  (a >= b) ? (a) : (b)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top