To switch logic in C++ by engine version you can use:

#if ENGINE_MAJOR_VERSION > 4
  //logic for UE 5 and higher
#endif
 
#if ENGINE_MAJOR_VERSION == 4 && ENGINE_MINOR_VERSION > 20
  //logic for UE 4.21 and higher
#endif