2013-06-25 12 views
14

Jeśli chcę wyodrębnić typ const odniesienia (jak podwójny z podwójnym & const), muszę używać:std :: remove_reference lub std :: remove_cv first?

typename std::remove_cv<typename std::remove_reference<Type>::type>::type 

lub

typename std::remove_reference<typename std::remove_cv<Type>::type>::type 

?

Odpowiedz

15

Najpierw użyj remove_reference. remove_cv usuwa tylko kwalifikatory najwyższego poziomu, aw przypadku odniesień nie ma żadnych (lub jest ignorowanych).

Przykładem, który przedstawia różnicę!

#include <iostream> 
#include <type_traits> 

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

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

int main() 
{ 
    std::cout << std::is_same<typename Remove_cv_ref<const int&>::type, int>::value; // 1 
    std::cout << std::is_same<typename Remove_ref_cv<const int&>::type, int>::value; // 0 
} 

Live demo.

4
typename std::remove_cv<typename std::remove_reference<Type>::type>::type 

ponieważ pierwszy remove_reference<const double&>::type jest const double, następnie remove_cv<const double>::type jest double.

Ale jeśli masz C++ 11, spójrz na std::decay.

+7

'std :: decay' = [' Unqualified'] (http://flamingdangerzone.com/cxx11/2013/02/ 25/even-more-traits.html # unqualified_types), dwa implikują inną semantykę. – Xeo

+1

@Xeo Tak, masz rację. (Ale gdy 'T' nie jest ani funkcją, ani tablicą (co było w przypadku' const double & ') to' zepsucie :: type' jest takie samo jak 'remove_cv :: type> :: type'.) (Powiedziałem też "spójrz na", a nie "używaj raczej" ^^) –

Powiązane problemy