gpt4 book ai didi

c++ - 将 GCC 的 typeof() 扩展与成员访问相结合

转载 作者:太空狗 更新时间:2023-10-29 21:25:03 25 4
gpt4 key购买 nike

我正在开发一个通过模板使用静态多态性的 C++ 库。之所以这样设计,是因为目标是一个堆栈小的嵌入式系统,通常有利于inline。成员函数以节省堆栈使用量。

静态多态性模板的使用意味着事件发射器(通常是设备驱动程序)类型的名称通常长得令人讨厌:

class DeviceThatUsesSPI<class SPI_BUS_TYPE> {

public:
class DeviceEvent : public Event<DeviceThatUsesSPI> {};

// and the rest of the device driver implementation, including
// the code that emits that event.

}

SomeSpecificGpioBus gpio_bus();
SoftwareSpiBus<typeof(gpio_bus)> spi_bus(&gpio_bus);
DeviceThatUsesSPI<typeof(spi_bus)> device(&spi_bus);

如您所见,我们使用 GCC typeof扩展运算符以避免写出令人讨厌的完整类型名称 DeviceThatUsesSPI<SoftwareSpiBus<SomeSpecificGpioBus>>反复。这在我们尝试过的所有地方都非常有效,直到今天我试图用它来访问表示事件的嵌套类。在我当前的示例中,这是一个模板特化,实现编译时事件处理程序绑定(bind):

template<>
inline void event_handler<typeof(device)::ExampleEvent>(typeof(device) *emitter) {
// event handler implementation...
}

但是,我还在一个更小的变量声明示例中尝试过:

typeof(device)::ExampleEvent event;

在这两种情况下,G++ 都无法解析带有语法错误的表达式。我假设这是因为在标准 C++ 语法中没有 :: 的情况。跟随除标识符之外的任何内容,并且解析器在遇到冒号时无法回溯并将第一部分视为一种类型。

然而,the GCC manual about typeof 对该运营商做出以下 promise :

A typeof construct can be used anywhere a typedef name can be used. For example, you can use it in a declaration, in a cast, or inside of sizeof or typeof.

如果我替换 typeof 的两个用途在我使用 typedef 的示例中,G++ 很高兴:

typedef typeof(device) device_type;

template<>
inline void event_handler<device_type::ExampleEvent>(typeof(device) *emitter) {
// event handler implementation...
}

device_type::ExampleEvent event;

因此,这进一步加深了我的怀疑,即编译器可以接受我在语义上编写的内容,但语法不允许我表达它。虽然使用 typedef 间接寻址确实让我可以工作代码,但我更愿意找到一种方法使事件处理程序声明自包含,以方便该库的用户。有没有办法写typeof运算符来消除解析歧义,以便我可以使事件声明成为一行?

最佳答案

根据 a bug report against GCC这是一个已知问题,已为 GCC 4.7 修复。升级 GCC 才是长久之计。

错误报告描述了使用类模板作为间接绕过旧版本解析器的进一步解决方法:

class SameType<T> {
public:
typedef T R;
}
T<typeof(device)>::ExampleEvent event;

这比 typedef 更好,因为它泛化到所有事件类型,但对用户来说仍然不自然。

应用于新标准decltype 运算符的相同问题实际上是a C++11 specification change 的主题。阐明了有关类型解析的规则,以使其按预期工作。

关于c++ - 将 GCC 的 typeof() 扩展与成员访问相结合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14669982/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com