我在模板化类的成员上使用decltype
时遇到了我以前从未见过的情况。我想做一个更好的make_unique
这样更改成员上的类型不会导致修复make_unique
调用。我想使用decltype(member)::element_type
作为make_unique
的类型来避免这种情况,但遇到了错误。这是一个显示错误的简单片段(我理解为什么显示它(:
#include <memory>
template<typename T>
struct foo
{
foo()
{
// g++ gives:
// dependent-name 'decltype (((foo<T>*)this)->foo<T>::p_)::element_type' is parsed as a non-type, but instantiation yields a type
// say 'typename decltype (((foo<T>*)this)->foo<T>::p_)::element_type' if a type is meant
//
// How can I atleast remove the class name from the type?
p_ = std::make_unique<decltype(p_)::element_type>();
// g++ gives:
// dependent-name 'decltype (p)::element_type' is parsed as a non-type, but instantiation yields a type
// say 'typename decltype (p)::element_type' if a type is meant
//
// makes sense since p here is dependent on T
std::unique_ptr<T> p = std::make_unique<decltype(p)::element_type>();
// This one is fine, makes sense, since the type is known
std::unique_ptr<int> p2 = std::make_unique<decltype(p2)::element_type>();
}
std::unique_ptr<T> p_;
};
int main()
{
foo<int> f;
return 0;
}
我的问题是,有没有一种很好/漂亮的方法可以从decltype
值中删除"是成员"((foo<T>*)this)->foo<T>::p_)
(部分,以便至少我可以使用相同的修复程序并简单地提供对成员变量p_
typename
?g++
建议的长修复似乎有点丑陋。
发布 5 分钟后,我有一个我可以做的想法
p_ = std::make_unique<decltype(std::remove_reference(*p_)::type)>();
但这似乎给出了解析错误。
您可以简单地在decltype()
之前放置一个typename
。
我的意思是
p_ = std::make_unique<typename decltype(p_)::element_type>();