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;
...
}
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.
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 [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 typedef T T
are illegal C++.type
, e.g.:
typedef T type;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With