显式调用模板参数的typedef的析构函数

显式调用模板参数的typedef的析构函数

本文介绍了C ++:显式调用模板参数的typedef的析构函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下内容:

template <typename X> struct A {
    typedef X _X;
};

template <typename Y> struct B { // Y is struct A
    typename Y::_X x;
    void call_destructor () {
        x.~Y::_X(); // This doesn't work
        x.Y::~_X(); // This as well
    }
};

不会编译,说

限定类型与析构函数名称不匹配

使用关键字 typename 在调用之前也无法正常工作。但是,确实会编译以下内容:

Using the keyword typename before the call also does not work. However, the following does compile:

template <typename Y> struct B {
    typename Y::_X x;
    typedef typename Y::_X __X;
    void call_destructor () {
        x.~__X(); // This works
    }
};

有人可以向我解释原因吗,没有<$ c $可以采取任何措施c> typedef ?

Can someone explain to me why, and is there any way to make do without the typedef?

推荐答案

x.~Y::_X(); // This doesn't work

是语法错误,我相信编译器会将其解析为调用 _X 〜Y

Is a syntax error, I believe the compiler parses it as calling _X in ~Y

您调用包含 :: 的析构函数,最后两个类型名称必须表示相同的类型

In the second case, when you call a destructor containing ::, the last two type names must denote the same type

s.A::~B();

其中 A B 必须为同一类型。 A B 都在以前的说明符指定的范围内查找(如果有的话)

where A and B must be the same type. A and B are both looked up in the scope specified by previous specifiers, if any

x._X::~_X();     // error, can't find _X in current scope

找不到逻辑

x.Y::_X::~_X();           // error, _X is dependent name
x.typename Y::_X::~_X();  // error, typename cannot be here

由于 Y :: _ X 是,<$ c $必须使用c> typename 消除其作为类型的歧义,但是析构函数的语法不允许表达式中包含 typename 。最终结果是必须使用X =类型名Y :: _ X使用类型别名

Since Y::_X is a dependent name, typename is required to disambiguate it as a type, but the grammar of destructors doesn't admit a typename within the expression. The end result is you must use a type alias

using X = typename Y::_X;
x.~X();

另一方面,编写和忘记析构函数调用的最简单方法就是

On the other hand the easiest way to write-and-forget a destructor call is simply

x.~decltype(x)();

但是gcc和msvc无法编译它。

but gcc and msvc fails to compile this.

这篇关于C ++:显式调用模板参数的typedef的析构函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 03:36