Reputation:
What's the best way to create an alias for a templated class in C++?
template<typename T>
class Dummy1
{
public:
Dummy1(T var) : myVar1(var) {
}
~Dummy1() {
}
private:
T myVar1;
};
C style would be:
typedef Dummy1<int> DummyInt;
In C++, as far as I know, I would write:
class DummyInt : public Dummy1<int>
{
DummyInt(int a) : Dummy1<int>(a) { }
~DummyInt() { }
}
Is there a better/shorter way? Cause this way when I inherit from the base, I have to declare the constructors every time.
I need an alias for Dummy1<int>
otherwise I need to use the template option through the entire code (like pointers and references). But I would like to not do this.
Upvotes: 2
Views: 2825
Reputation: 170065
If you just must use inheritance then you can avoid repeating the constructors in c++11 and onward by just inheriting them:
struct DummyInt : Dummy1<int> {
using Dummy1::Dummy1;
};
Otherwise, just use an alias like you do. If you want it to not be the "C way" you can employ the modern C++ style:
using DummyInt = Dummy1<int>;
Upvotes: 8
Reputation: 9733
You can just as well use a typedef or a using in C++
typedef Dummy1<int> DummyInt;
using DummyInt = Dummy1<int>;
You dont see typedef anymore in modern C++ code IMO.
Upvotes: 4
Reputation: 1535
I prefer (C++11 and after):
using DummyInt = Dummy1<int>;
No reason not to use an alias here, in my opinion.
Upvotes: 3