首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++11解密类型:如何声明指针指向的类型?

C++11解密类型:如何声明指针指向的类型?
EN

Stack Overflow用户
提问于 2015-02-09 07:39:06
回答 2查看 2.2K关注 0票数 5

我有以下代码:

代码语言:javascript
复制
#include <memory>

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

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

这将导致以下错误消息:

代码语言:javascript
复制
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是一个非常长且非常复杂的类型,我如何使该代码与解密类型一起工作?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-02-09 07:46:43

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

票数 13
EN

Stack Overflow用户

发布于 2015-02-09 07:46:54

您可以在模板化类中使用ty胡枝子,然后使用模板专门化,如下所示

代码语言:javascript
复制
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);
}
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28404919

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档