使用const引用删除引用 [英] Remove reference with const references
问题描述
对于参数化类C,我想始终使用原始类型,而不考虑指针,const或引用修饰符。
For a parametric class C, I want to get always the "primitive" type irrespective of pointer, const or reference modifiers.
template<typename __T>
class C
{
public:
typedef std::some_magic_remove_all<__T>::type T;
}
int main()
{
C<some_type>::type a;
}
例如,对于 some_type
等于:
-
int&
-
int **
-
int *&
-
int const&&&
-
int const * const
- 等等
int&
int**
int*&
int const &&
int const * const
- and so on
我想要 a
始终为 int
类型。如何实现?
I want a
is always of type int
. How can I achieve it?
推荐答案
template<class T> struct remove_all { typedef T type; };
template<class T> struct remove_all<T*> : remove_all<T> {};
template<class T> struct remove_all<T&> : remove_all<T> {};
template<class T> struct remove_all<T&&> : remove_all<T> {};
template<class T> struct remove_all<T const> : remove_all<T> {};
template<class T> struct remove_all<T volatile> : remove_all<T> {};
template<class T> struct remove_all<T const volatile> : remove_all<T> {};
//template<class T> struct remove_all<T[]> : remove_all<T> {};
//template<class T, int n> struct remove_all<T[n]> : remove_all<T> {};
我最初也剥离了扩展区(数组),但Johannes注意到这会导致 const char []
,问题没有提及。如果我们还想要删除数组(另见评论中提到的想法),下面的内容不会太复杂:
I originally also stripped extents (arrays), but Johannes noticed that this causes ambiguities for const char[]
, and the question doesn't mention them. If we also want to strip arrays (see also ideas mentioned in the comments), the following doesn't complicate things too much:
#include <type_traits>
template<class U, class T = typename std::remove_cv<U>::type>
struct remove_all { typedef T type; };
template<class U, class T> struct remove_all<U,T*> : remove_all<T> {};
template<class U, class T> struct remove_all<U,T&> : remove_all<T> {};
template<class U, class T> struct remove_all<U,T&&> : remove_all<T> {};
template<class U, class T> struct remove_all<U,T[]> : remove_all<T> {};
template<class U, class T, int n> struct remove_all<U,T[n]> : remove_all<T> {};
或使用辅助类但单个模板参数:
or with a helper class but a single template parameter:
#include <type_traits>
template<class T> struct remove_all_impl { typedef T type; };
template<class T> using remove_all =
remove_all_impl<typename std::remove_cv<T>::type>;
template<class T> struct remove_all_impl<T*> : remove_all<T> {};
template<class T> struct remove_all_impl<T&> : remove_all<T> {};
template<class T> struct remove_all_impl<T&&> : remove_all<T> {};
template<class T> struct remove_all_impl<T[]> : remove_all<T> {};
template<class T, int n> struct remove_all_impl<T[n]> : remove_all<T> {};
这是正常的,如果所有的变种开始看起来相同; - )
It is normal if all the variants start looking about the same ;-)
这篇关于使用const引用删除引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!