Typedef compilation error on function overload

Why can't I compile program 1 when program 2 is working fine? Why is this behavior different?

Program 1:

#include <iostream>
typedef int s1;
typedef int s2;

void print(s1 a){ std::cout << "s1\n"; }
void print(s2 a){ std::cout << "s2\n"; }

int main() {
        s1 a;
        s2 b;

        print(a);
        print(b);

        return 0;
}

Program 2:

#include <iostream>
typedef struct{int a;} s1;
typedef struct{int a;} s2;

void print(s1 a){ std::cout << "s1\n"; }
void print(s2 a){ std::cout << "s2\n"; }
int main() {
        s1 a;
        s2 b;

        print(a);
        print(b);

        return 0;
}

This is an error reproduced from a template class. How to check if two arguments of a template are of the same type (in case of program 1)

+3
source share
3 answers

Typedefs do not define new types; they simply create aliases for existing types. In your first program s1and s2both are aliases for int. In your second program, they are aliases for two different structures that are simply identical in structure.

, :

// Semantically identical to program 2
typedef struct a {int a;} s1;
typedef struct b {int a;} s2;

, , , :

// Different from program 2. This will draw a compile error.
struct s {int a;};
typedef struct s s1;
typedef struct s s2;
+10

int - : , , - int.

struct{int a;} - , struct{int a;}, - s1 s2 2.

, :

typedef struct{int count;} apples;
typedef struct{int count;} airplanes;

? . . , int , structs - int , , structs do.

typedef - .

, 1 2 , 1 ( ) : print(int). 2 : print([first struct type]) print([second struct type]).

+2

, 1 s1 s2 , 2 . , .

0

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


All Articles