Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get base type of a template type (remove const/reference/etc.)

Is there a type traits template which returns the base type of a given type. By base type I mean the type with all value modifiers, const, volatile, etc. stripped off. For example, using a hypothetical traits function:

base<int>::type == int
base<int const>::type == int
base<int&>::type == int

I'm aware of remove_const and remove_reference and am currently just using them in combination. I'm wondering if however there exists already such a trait and perhaps if there is a proper name to what I am referring?

like image 591
edA-qa mort-ora-y Avatar asked May 25 '13 12:05

edA-qa mort-ora-y


3 Answers

I would probaby define a type alias such as:

template<typename T>
using base_type = typename std::remove_cv<typename std::remove_reference<T>::type>::type;

Note that, in an article no longer available, R. Martinho Fernandes proposed the name Unqualified for such a type alias.

The standard type trait std::decay, on the other hand does the same as the above and something more for array and function types, which may or may not be what you want.

like image 126
Andy Prowl Avatar answered Oct 14 '22 15:10

Andy Prowl


try std::decay. It mimicks what happens when you pass arguments to functions by value: strips top-level cv-qualifiers, references, converts arrays to pointers and functions to function pointers.

Regards, &rzej

like image 28
Andrzej Avatar answered Oct 14 '22 13:10

Andrzej


Obviously it depends on what exactly you want to remove from the type. std::decay could be what you are looking for (removes references, const/volatile, decays array to pointer and function to function pointer). If you don't want the array to pointer and function to functionpointer decay, you need to stick with std::remove_reference and std::remove_cv (removes const and volatile). Of course you could combine the two into your own typetrait to make using it easier.

like image 35
Grizzly Avatar answered Oct 14 '22 14:10

Grizzly