Can we alias a class name the way we do in namespaces?
For example:
namespace longname{ }
namespace ln = longname;// namespace aliasing
class LONGNAME {};
class LN = LONGNAME; // how to do class name aliasing, if allowed?
Namespace Alias Qualifier(::) makes the use of alias name in place of longer namespace and it provides a way to avoid ambiguous definitions of the classes. It is always positioned between two identifiers. The qualifier looks like two colons(::) with an alias name and the class name. It can be global.
You can also create an alias for a namespace or a type with a using alias directive.
Inside a namespace, no two classes can have the same name.
namespace alias definition Namespace aliases allow the programmer to define an alternate name for a namespace. They are commonly used as a convenient shortcut for long or deeply-nested namespaces.
Simple:
typedef LONGNAME LN;
Typedefs are used in C++ a bit like "variables which can store types". Example:
class Car
{
public:
typedef std::vector<Wheel> WheelCollection;
WheelCollection wheels;
};
By using Car::WheelCollection
everywhere instead of std::vector<Wheel>
, you can change the container type in one place and have all your code reflect the changes. This is the C++ way to abstract data types (whereas eg. in C# you'd have a property returning IEnumerable<Wheel>
).
Beside the answers already provided using the keyword typedef
, you also can use the keyword using
since C++11. IMHO it looks more consistent regarding the aliasing.
namespace longname{ }
namespace ln = longname;// namespace aliasing
class LONGNAME {};
using LN = LONGNAME; // "class aliasing"
In addition, with using
you are able to alias template classes (How to typedef a template class?) by using alias templates.
template<typename T> class LONGNAME {};
template<typename T> using LN = LONGNAME<T>; // alias template
You can use the typedef keyword:
typedef LONGNAME LN;
You can also do something like:
typedef class {
...
} LN;
Edit: You may run into trouble when using templates though. See here for a possible solution.
typedef int mark; // for in built data types
class abc
{
};
typedef abc XYZ; // for user written classes.
Typedef allows you to alias a class or datatype name with a more context sensitive name corresponding to the scenario.
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