Function overloading for "integral" types

Suppose that there are types of “temperature” (T) and “distance” (D). Both can indeed be declared as regular typedefs:

typedef int T; // might be C++11 'using' 
typedef int D;

But if I need overloaded functions:

void f(T) {}  
void f(D) {}

it will not work because both types are identical.

What is the most advanced C ++ way to implement such an overload?

Clearly, for these types should be distinguishable to the compiler.

+4
source share
2 answers

BOOST_STRONG_TYPEDEF made just for this purpose.

+7
source

If you want them to be distinguishable, I would go for a structure with a conversion operator.

struct T {
   int value;
   operator int() const {
       return value;
   }
}

A simple class of values.

- , , T .

T operator "" _t(unsigned long long int v){ return {v};}
+6

Source: https://habr.com/ru/post/1548452/


All Articles