从decltype中删除类成员类型的部分

问题描述 投票:0回答:1

我遇到了一个我以前从未见过的情况,当时在模板类的成员上使用了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;
}

我的问题是,有没有一种很好的方法来从(foo<T>*)this)->foo<T>::p_)值中删除“是...的成员”(decltype)部分,以便至少我可以使用相同的修复程序并简单地提供[C0 ]在成员变量typename上? p_建议的长期修复似乎很丑。

发布后5分钟,我有想法可以做

g++

但是这似乎会带来解析错误。

c++11 g++ decltype
1个回答
1
投票

您可以简单地将p_ = std::make_unique<decltype(std::remove_reference(*p_)::type)>(); 放在typename之前。

我的意思是>

decltype()
© www.soinside.com 2019 - 2024. All rights reserved.