要与"if constexpr"一起使用的编译时消息(在预处理器之后)

Compilation time message (after preprocessor) to use with `if constexpr`

本文关键字:quot 消息 预处理 之后 处理器 constexpr if 一起 要与 编译      更新时间:2023-10-16

我正在使用if constexpr来测试类中方法的存在性。如果该方法不存在,我希望告诉用户该函数被忽略,他应该实现它,但它不是强制性的。

这个想法是给出一个类似于#warning的消息,但预处理器是在模板之前处理的,因此这永远不会起作用。

C++17中是否有编译时间反馈选项?或者有针对C++20的计划吗?

可运行的示例

template <typename State>
void callStateFunction(const State& state) {
if constexpr (false) {
state.method();
} else {
#warning The method State::method() was not implemented
}
}

我想这不是一个好的解决方案,但。。。

如果编译器激活了所有警告(例如,g++和clang++的-Wall(,则可以用生成警告的内容替换#warning行。

例如,一个未使用的(可能有一个会说话的名字(变量。

我试过

template <typename State>
void callStateFunction(const State& state) {
if constexpr (false) {
state.method();
} else {
int method_not_implemented[sizeof(State)];
}
}

用非方法值(例如callStateFunction(1)(调用,我得到

prog.cc: In instantiation of 'void callStateFunction(const State&) [with State = int]':
prog.cc:13:23:   required from here
prog.cc:7:9: warning: unused variable 'method_not_implemented' [-Wunused-variable]
7 |     int method_not_implemented[sizeof(State)];
|         ^~~~~~~~~~~~~~~~~~~~~~

来自g++(磁头11.0.0(和

prog.cc:7:9: warning: unused variable 'method_not_implemented' [-Wunused-variable]
int method_not_implemented[sizeof(State)];
^
prog.cc:13:4: note: in instantiation of function template specialization 'callStateFunction<int>' requested here
callStateFunction(1);
^

来自clang++(头部11.0.0(

我建议未使用的变量取决于模板类型名称(State(,否则,如果我将非因变量定义为

int method_not_implement;

我收到来自clang++的警告

prog.cc:7:9: warning: unused variable 'method_not_implemented' [-Wunused-variable]
int method_not_implemented;
^

也不使用非方法对象调用函数。