Reputation: 6958
I'm consolidating 2 programs into one, and in 2 different files (I have many files), I have a typedef with the same name, different types though.
These types will be used in completely different parts of the program and will never talk to each other, or be used interachangely.
I can of cause just do a search replace in one of the files, but I was wondering if there is another solution to this.
Something like binding a typedef to a specific file. Or making a typedef local to a class and it's subclasses.
Thanks
Upvotes: 6
Views: 5123
Reputation: 320631
typedef
s are always "local to a file". So it is not exactly clear what you mean by "making it local to a file". Typedef does not introduce an entity with its own linkage, it simply creates an alias to an existing type. For that reason the problem of "making it local to a file" simply does not exist. Each typedef is only visible in the translation unit (file) in which it is declared. So, if you can make sure that your identically named typedef
s never meet each other in a common translation unit, you problem is formally solved.
It is not a good programming practice though to have the same typedef-name refer to different types in different files, unless these files are naturally separated somehow (like belong to different libraries, or something like that).
Otherwise, you can always rename one of the typedef
s, or make it a class member or a namespace member. Keep in mind though that in general case the making a typedef
member of a class will require virtually the same kind of effort as renaming it: the references to that typedef
will have to be updated in every place in which they are present. Namespaces might be a bit easier, since with namespaces you can use using
directive.
But again, if your typedef
s are only referrd from two disjoint sets of files, then the problem does not formally exist. If there are files that are supposed to use both typedef
s, then the effort you'll have to spend fixing these files will be equivalent to renaming the typedef
s (regardless of the method you finally choose).
Upvotes: 7
Reputation: 28757
[...]Or making a typedef local to a class and it's subclasses.
Well, that's simple:
struct A
{
typedef int X;
};
struct B : A
{
X a;
};
struct C
{
typedef double X;
};
Typedefs are scoped in C++.
Upvotes: 2
Reputation: 70030
You can encapsulate those typedef
inside a namespace
:
namespace N1 {
typedef int T;
}
namespace N2 {
typedef int T;
}
And in whatever file you want to use first typedef
simply declare:
using namespace N1;
same thing for the other one also.
Upvotes: 4