C++ 正在销毁此对象时推断对象的模板类型
情境:我有一个deque声明为C++ 正在销毁此对象时推断对象的模板类型,c++,templates,C++,Templates,情境:我有一个deque声明为deque tab,我想用推断的模板参数销毁它。我尝试了tab.~deque(),这给了我编译器错误: Csrt.cpp: In function 'int main(int32_t, char**)': Csrt.cpp:303:34: the type being destroyed is 'std::deque<long long int>', but the destructor refers to 'std::deque<long lo
deque tab
,我想用推断的模板参数销毁它。我尝试了tab.~deque()
,这给了我编译器错误:
Csrt.cpp: In function 'int main(int32_t, char**)':
Csrt.cpp:303:34: the type being destroyed is 'std::deque<long long int>',
but the destructor refers to 'std::deque<long long int&>'
tab.~deque<__decltype(tab.at(0))>();
^
Csrt.cpp:在函数“int main(int32_t,char**)”中:
Csrt.cpp:303:34:正在销毁的类型是“std::deque”,
但是析构函数引用“std::deque”
tab.~deque();
^
问题是:这样做可行吗?我知道我不想做的事情:创建虚拟变量。例如:
auto-dummy=tab.at(0)
我希望的是可行的:一行析构函数。
我也尝试了:
tab.~deque()
,结果:同上。我想这就是所需要的全部信息。提前谢谢。编写一个函数来推断类型通常比自己指定类型更容易。那么:
template <typename T>
void murder(T& t)
{ t.~T(); }
您正在对基于堆栈的对象调用析构函数,因此我认为您对稍后使用placement new感兴趣,类似于本文 在Ubuntu 10.04上使用g++4.4.3,只需使用无模板修饰的Destructor即可为我编译和运行:
tab.~deque();
有什么我遗漏的吗
我还不能评论别人的帖子,但答案很好。除此之外,这里还有一篇关于。主题的相当长但内容丰富的SO帖子。问题是deque中的
at
成员函数定义如下:
intmax_t &at(size_t pos);
因此,您的decltype(x.at(0))
实际上解析为intmax\u t&
您可以使用remove\u参考
类型特征:
#include <type_traits>
x.~deque<std::remove_reference<decltype(x.at(0))>::type>();
如果您真的需要使用类型参数调用析构函数,那么快速修复方法就是执行类似于
std::decay::type
Awesome的操作!迄今为止最好的答案!非常感谢。
#include <type_traits>
x.~deque<std::remove_reference<decltype(x.at(0))>::type>();
x.~deque<decltype(x)::value_type>();
x.~deque();