Reputation: 1997
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?
Upvotes: 26
Views: 24032
Reputation: 1
I assume typedef, as others have mentioned, is the best answer. In my Project that didn't work though due to other reasons, so I had to resort to another solution:
class LN: public LONGNAME {
//inherit ALL constructors
using LONGNAME::LONGNAME;
}
Basically you create a child class that's identical to the parent class.
If that comes with problems I haven't noticed, feel free to correct me.
Upvotes: 0
Reputation: 5334
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
Upvotes: 22
Reputation: 56966
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>
).
Upvotes: 34
Reputation: 11787
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.
Upvotes: 1
Reputation: 22031
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.
Upvotes: 6