Search code examples
c++preprocessoroverloading

Is it possible in C++ to conditionally compile code if types are (not) equal?


Currently I have a problem with code portability from 64 (back) to 32 bit. The problem is, that a method of a class is overloaded for 64 bit platforms that conflicts with another overload on 32 bit platforms.

The two methods look like this:

void myfunc(unsigned o);
void myfunc(size_t o);

On 32 bit architectures, they look identical to the compiler and throw some error.

So, the question is, is it possible to do something like this:

void myfunc(unsigned o);
#if typeid(unsigned) != typeid(size_t)
void myfunc(size_t o);
#endif

My current solution looks like this:

void myfunc(unsigned o);
#if __WORDSIZE == 64
void myfunc(size_t o);
#endif

But there is some bad feeling left, that WORDSIZE is not the best fit, because it does not necessarily mean, that the types are not the same.

OK, here is the problematic place line 705 and 706, that produce an error when compiling on 32-bit ARM.

ceph/src/include/buffer.h


Solution

  • This might be an option using templates:

    #include <iostream>
    
    class A {
    public:
        template<typename T>
        std::enable_if_t<std::is_same<T, int>::value || 
        std::is_same<T, unsigned>::value ||
        std::is_same<T, std::size_t>::value >
        advance(T o) {
            std::cout << "s" << std::endl;
            A::advance<unsigned>(static_cast<unsigned>(o));
        }
    };
    
    template<>
        void A::advance(int o) = delete;
    
    template<>
        void A::advance(unsigned o) {
            std::cout << "u" << std::endl;
        }
    
    int main()
    {
      A a;
    
      unsigned x;
      std::size_t y;
      int z;
      char p;
    
      a.advance(x);
      a.advance(y);
      //a.advance(z);
      //a.advance(p);
    
      return 0;
    }