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?
" typename " is a keyword in the C++ programming language used when writing templates. It is used for specifying that a dependent name in a template definition or declaration is a type.
typedef is defining a new type for use in your code, like a shorthand. typedef typename _MyBase::value_type value_type; value_type v; //use v. typename here is letting the compiler know that value_type is a type and not a static member of _MyBase . the :: is the scope of the type.
In general, C++ needs typename because of the unfortunate syntax [*] it inherits from C, that makes it impossible without non-local information to say -- for example -- in A * B; whether A names a type (in which case this is a declaration of B as a pointer to it) or not (in which case this is a multiplication ...
They are largely the same, except that: The alias declaration is compatible with templates, whereas the C style typedef is not.
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);
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;
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