Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template alias for another alias [duplicate]

I have some problem with 'using' keyword in c++11. This piece of code should create alias for pointer to another type.

template <typename T>
class SomeClass
{
    typedef typename std::add_pointer<T>::type pointer;

    template <typename U>
    using rebind_pointer = typename std::pointer_traits<pointer>::rebind<U>;
}

SomeClass<int> obj;

But in gcc 4.7 I've got compile error:

typename std::pointer_traits<int*>::rebind names template<class _Up> using rebind = _Up*, which is not a type

I found out that pointer_traits::rebind is a template alias itself so maybe that is problem ?

like image 760
eupp Avatar asked Jul 14 '15 14:07

eupp


People also ask

What is alias declaration in C++?

You can use an alias declaration to declare a name to use as a synonym for a previously declared type. (This mechanism is also referred to informally as a type alias). You can also use this mechanism to create an alias template, which can be useful for custom allocators.

Should I use typedef or using?

The major limitation of typedef is that it does not work with templates. Both using and typedef perform the same mechanically while working with non-templates. However, while defining the more complex template aliases, function-pointer aliases, and array reference aliases, the using statement emerges as a clear winner.

Should I use typedef or using in C++?

In C++, 'using' and 'typedef' performs the same task of declaring the type alias. There is no major difference between the two. 'Using' in C++ is considered to define the type synonyms. This method is also known as alias- declaration.

Is using the same as typedef?

They are equivalent, from the standard (emphasis mine) (7.1. 3.2): A typedef-name can also be introduced by an alias-declaration. The identifier following the using keyword becomes a typedef-name and the optional attribute-specifier-seq following the identifier appertains to that typedef-name.


1 Answers

You need to tell the compiler to parse rebind as a template:

template <typename U>
using rebind_pointer = typename std::pointer_traits<pointer>::template rebind<U>;
//                                                            ^^^^^^^^

This is necessary because std::pointer_traits<pointer> is dependent on a template parameter (T).

See this question for more details about when and why you need to use the template keyword.

like image 107
TartanLlama Avatar answered Sep 19 '22 16:09

TartanLlama