Reputation: 81
I know that the "using" keyword could be used as template alias and type alias, but I didn't see anyone has mentioned that "typedef typename" could be replaced by "using". So could it?
Upvotes: 8
Views: 6611
Reputation: 70267
A declaration of the following form
typedef typename something<T>::type alias;
can be replaced by
using alias = typename something<T>::type;
The typename
is still necessary, but it does look neater, and having that =
in the middle of the line is aesthetically pleasing since we are defining an alias. The main selling point of using is that it can be templated.
template <typename T>
using alias = typename something<T>::type;
You can't do that with typedef
alone. The C++98 equivalent would be this slightly monstrous syntax.
template <typename T>
struct Alias {
typedef typename something<T>::type type;
};
// Then refer to it using typename Alias<T>::type.
// Compare to the C++11 alias<T>, which is much simpler.
The other major selling point of using
over typedef
is that it looks much cleaner when defining function aliases. Compare
// C++98 syntax
typedef int(*alias_name)(int, int);
// C++11 syntax
using alias_name = int(*)(int, int);
Upvotes: 7
Reputation: 14589
using
can replace type declaration in case if you use it as alias of another type or if you can declare this type. Syntax is:
using identifier attr(optional) = type-id ; (1)
template < template-parameter-list > using identifier attr(optional) = type-id ; (2)
type-id - abstract declarator or any other valid type-id (which may introduce a new type, as noted in type-id). The type-id cannot directly or indirectly refer to identifier.
So, this cannot be replaced by single using
, you need two:
typedef struct MyS
{
MyS *p;
} MyStruct, *PMyStruct;
Upvotes: 1