我有一个事件处理程序类,它使用模板参数来设置事件类型。我想将这些事件类型强制为一字节大小的枚举类。针对大小的静态断言不是问题,但我无法在网上找到有关如何静态区分enum和enum class 的信息。
我现在的解决方案是使用C++ 前端实现语法扩展来断言枚举,然后断言正确的大小。在大多数平台上这是有效的,因为枚举使用int类型(通常大于一个字节)。
但这会导致稍微误导性的错误消息。我喜欢彻底。
我可以做哪些检查来传递类枚举,但会因常规的旧枚举而失败?
我不能使用type_traits,因为我使用的编译器(avr-gcc)不支持它。然而type_traits,当需要增加时,我会不断实施我自己的。因此,有关解决方案的任何提示type_traits仍然有用!
最小的例子:
// Event types
enum class tPass : uint8_t {};
enum class tFailSize : uint16_t {}; // Fail on size!
enum tFailType {}; // Currently fails on size, would like to fail on type!
// Event handler
template <typename TEvent>
class tEventHandler
{
static_assert(__is_enum(TEvent), "Must be class enum!"); // Doesn't really check for CLASS …Run Code Online (Sandbox Code Playgroud) 我正在开发一个库,它允许用户设置关键类型别名,或者通过预处理器指令来完成。根据设计,此类型别名(或指令)在库中未声明。因此,在开发代码时,我会收到这种未声明类型的烦人的错误消息和波形曲线。如果我在某处为其声明一个临时类型,则可以避免这种情况。但是,我不喜欢在使用代码时声明它,然后在发布代码时将其删除的想法。它也容易出现错误,因为我很容易忘记删除它。
我的问题是: 我可以为 VS Code 的静态分析(IntelliSense?C/C++ 扩展)定义预处理器指令吗?
这会让我考虑像定义良好的类型别名会产生什么一样的分析。并避免烦人的错误消息/曲线。
最小可重现示例:
tCore.hpp
#pragma once
#include <string>
// User is responsible of declaring the tCore type
// tCore interface methods
template<typename TCore>
std::string printImpl();
Run Code Online (Sandbox Code Playgroud)
tPrint.hpp
#pragma once
#include <iostream>
class tPrint {
public:
tPrint() = default;
void print() const {
std::cout << printImpl<tCore>() << std::endl; // <-- Static analysis error here!
}
};
Run Code Online (Sandbox Code Playgroud)
tFoo.hpp - tCore 候选者
#pragma once
#include <string>
#include "tCore.hpp"
struct tFoo {};
template<>
std::string printImpl<tFoo>() {
return "tFoo"; …Run Code Online (Sandbox Code Playgroud) c++ c-preprocessor preprocessor-directive visual-studio-code