marcelnijman
marcelnijman

Reputation: 604

how to create a static template function to a pointer class?

My template class A contains a function that calls a static function of the template class:

template <typename T>
void A<T>::fun() {
    T obj = T::create();
    ....
}

How should I modify this if I want this code to work when T = B* ? I know I can't do (*T)::create(), but conceptually, that is what I want.

Upvotes: 2

Views: 115

Answers (1)

Andy Prowl
Andy Prowl

Reputation: 126432

You could use the std::remove_pointer type trait:

#include <type_traits>

template <typename T>
void A<T>::fun() {
    T obj = std::remove_pointer<T>::type::create();
//          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    // ...
}

Where both std::remove_pointer<U*>::type and std::remove_pointer<U>::type give U.

Upvotes: 5

Related Questions