Roberto P. Romero
Roberto P. Romero

Reputation: 387

Can you alias a template members in C++?

I want to rename or alias some parts of the stl so they are compliant with the naming conventions of my project. So far renaming types is easy

template<class Type>
using Vector = std::vector<Type>;

I tried doing something similar to alias members:

template<class Type>
using Vector::PushBack = std::vector<Type>::push_back;
// and
template<class Type>
using Vector<Type>::PushBack = std::vector<Type>::push_back;

Sadly this approach does not work for member variables. Can I alias members? How?

Upvotes: 0

Views: 156

Answers (2)

Timo
Timo

Reputation: 9835

You can only alias types or type templates. A member function is not a type, thereofore you cannot alias it. However you can make a surrogate for it:

template <typename T>
auto push_back(std::vector<T>& vec, T&& val)
{
    return vec.push_back(std::forward<T>(val));
}

Upvotes: 3

Brainless
Brainless

Reputation: 1758

No, you can't alias member variables.

Cf https://learn.microsoft.com/en-us/cpp/cpp/aliases-and-typedefs-cpp?view=vs-2019: "You can use an alias declaration to declare a name to use as a synonym for a previously declared type"

What is the point of aliasing a variable, since you can directly call it?

Upvotes: 1

Related Questions