Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the point of "typedef sometype sometype"?

Tags:

c++

typedef

Lately I've run into the following construction in the code:

typedef sometype sometype;

Pay attention please that "sometype" stands for absolutely the same type without any additions like "struct" etc.

I wonder what it can be useful for?

UPD: This works only for user defined types.

UPD2: The actual code was in a template context like this:

template <class T>
struct E
{
   typedef T T;
   ...
}
like image 637
Alex Jenter Avatar asked Feb 04 '10 11:02

Alex Jenter


2 Answers

How about to make Template parameters visible to outside entities?

template <class Foo>
struct Bar
{
    typedef Foo Foo;
};

int main()
{
    Bar<int>::Foo foo = 4;
}

Note: this is actually not allowed in standard C++, but is specific to MSVC. See comments.

like image 161
Kaz Dragon Avatar answered Oct 13 '22 01:10

Kaz Dragon


Given your additional information about templates, we can now answer.

The use-case is when you want to specialize on the type of a template. One typical example is the following:

template <typename T>
struct nonconst {
    typedef T t;
};

template <typename T>
struct nonconst<T const> {
    typedef T t;
};

This effectively allows you to remove the const qualifier from any type:

nonconst<int>::t x;
nonconst<int const>::t y;
assert(typeid(x) == typeid(int));
assert(typeid(y) == typeid(int));

There are many similar use-cases, e.g. to add (or remove) the pointer qualifier from a type, provide defaults and specializations for certain types, etc.

However, notice the different casing of the type names! Equal types in typedef T T are illegal C++.[I stand corrected: §7.1.3.2] Furthermore, the de-fact naming standard (cemented by its use in Boost libraries) is to call the type name alias type, e.g.:

typedef T type;
like image 41
Konrad Rudolph Avatar answered Oct 12 '22 23:10

Konrad Rudolph