Kietz
Kietz

Reputation: 1406

Is it possible to extract type from a pointer template parameter?

Is it possible to define a template which takes a single pointer parameter and extracts the type pointed to?

extern int three = 3;
typename examine<&three>::pointed_type // int

Upvotes: 0

Views: 181

Answers (2)

danielschemmel
danielschemmel

Reputation: 11116

Yes, you would use partial specialization to achieve this, similar to the following:

template<typename T>
struct examine {
    typedef T pointed_type;
};

template<typename T>
struct examine<T*> {
    typedef T pointed_type;
};

To refer to your comment about usage of non-type template parameters, consider the following:

template<typename T, T* p>
struct foo { };

extern int three = 3;
foo<decltype(three), &three> bar;

As you can see, foo can indeed take a template parameter of &x, but to do so we first need to give it a type parameter (or restrict it to int*, which does not help at all). If this is not done, the name T is not that of any type when the template parameter p is defined.

There is no way at all to perform any kind of automatic deduction of T, since that would require the template arguments to be defined in the other order.

The closest you can get without using decltype is by defining a function template that gets a non-template argument that will cause the template type parameter to be deduced like so

template<typename T>
void deduce_argument_type(T const&)
{
    // here, the type T is (close to) that of your argument
}
deduce_argument_type(&three); // uses deduce_argument_type<int*>

Again, you cannot use this to get around the restriction on defining T before passing &three, since template parameter deduction only deduces any types to the right of those template parameters you passed.

Upvotes: 1

zneak
zneak

Reputation: 138031

There's already std::remove_pointer<T>::type in <type_traits> (C++11) that you can use.

Upvotes: 2

Related Questions