繁体   English   中英

C ++ 11 decltype:如何声明指针指向的类型?

[英]C++11 decltype: How to declare the type that a pointer points to?

我有以下代码:

#include <memory>

int main()
{
    int* a = new int(2);

    std::unique_ptr<decltype(*a)> p(a);
}

这会导致以下错误消息:

In file included from a.cpp:1:
In file included from /usr/bin/../lib64/gcc/x86_64-unknown-linux-gnu/4.9.2/../../../../include/c++/4.9.2/memory:81:
/usr/bin/../lib64/gcc/x86_64-unknown-linux-gnu/4.9.2/../../../../include/c++/4.9.2/bits/unique_ptr.h:138:14: error: '__test' declared as a pointer to a reference of type 'int &'
          static _Tp* __test(...);
                    ^
/usr/bin/../lib64/gcc/x86_64-unknown-linux-gnu/4.9.2/../../../../include/c++/4.9.2/bits/unique_ptr.h:146:35: note: in instantiation of member class 'std::unique_ptr<int &,
      std::default_delete<int &> >::_Pointer' requested here
      typedef std::tuple<typename _Pointer::type, _Dp>  __tuple_type;
                                  ^
a.cpp:7:35: note: in instantiation of template class 'std::unique_ptr<int &, std::default_delete<int &> >' requested here
    std::unique_ptr<decltype(*a)> p(a);
                                  ^
In file included from a.cpp:1:
In file included from /usr/bin/../lib64/gcc/x86_64-unknown-linux-gnu/4.9.2/../../../../include/c++/4.9.2/memory:81:
/usr/bin/../lib64/gcc/x86_64-unknown-linux-gnu/4.9.2/../../../../include/c++/4.9.2/bits/unique_ptr.h:227:33: error: 'type name' declared as a pointer to a reference of type 'int &'
               is_convertible<_Up*, _Tp*>, is_same<_Dp, default_delete<_Tp>>>>
                                       ^
a.cpp:7:35: note: in instantiation of template class 'std::unique_ptr<int &, std::default_delete<int &> >' requested here
    std::unique_ptr<decltype(*a)> p(a);
                                  ^
2 errors generated.

我理解原因是unique_ptr模板需要int类型,但decltype(*a)给出int& int是一个非常冗长和复杂的类型的情况下,如何使这个代码与decltype一起工作?

使用std::decay_t 这是通过值将参数传递给函数时应用的转换。

您可以在模板化类中使用typedef,然后使用模板特化,如下所示

template<typename T> struct unref {
  typedef T raw;
};
template<typename T> struct unref<T&> { 
  typedef T raw;
};

int main() {
    int* a = new int(2);
    std::unique_ptr<unref<decltype(*a)>::raw> p(a);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM