c++ - 使用 const 引用删除引用

标签 c++ templates c++11 std

对于参数类 C,无论指针、常量或引用修饰符如何,我都希望始终获得“原始”类型。

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
  • 等等

我希望a 始终是int 类型。我怎样才能实现它?

最佳答案

如果你想更多地使用标准库,你可以这样做:

#include <type_traits>
template<class T, class U=
  typename std::remove_cv<
  typename std::remove_pointer<
  typename std::remove_reference<
  typename std::remove_extent<
  T
  >::type
  >::type
  >::type
  >::type
  > struct remove_all : remove_all<U> {};
template<class T> struct remove_all<T, T> { typedef T type; };

删除内容直到不再改变类型。使用更新的标准,这可以缩短为

template<class T, class U=
  std::remove_cvref_t<
  std::remove_pointer_t<
  std::remove_extent_t<
  T >>>>
  struct remove_all : remove_all<U> {};
template<class T> struct remove_all<T, T> { typedef T type; };
template<class T> using remove_all_t = typename remove_all<T>::type;

关于c++ - 使用 const 引用删除引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14522496/

相关文章:

c++ - set<class>插入问题

c++ - Opencv:cvCaptureFromCAM 返回 NULL

c++ - 二叉树功能不适用于模板

c++ - 有一个很长的缓冲区,但只使用最后 1GB 字节的数据。

c++ - 全局数组分配——栈还是堆?

c++ - 如果参数类型可转换,则将函数类型转换为不同

c++ - "expected a ' > '"在类模板特化中?

c++ - 如何对 std::shared_ptr<Widget> 对象的容器进行排序?

c++ - std::async 有什么问题?

c++ - 如何访问可变模板参数包成员中存在的内部模板 typedef?