Ale*_*ues 6 c++ template-meta-programming c++17
我正在使用 anif 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
}
}
Run Code Online (Sandbox Code Playgroud)
我想这不是一个很好的解决方案,但是......
如果您的编译器激活所有警告(-Wall例如,对于 g++ 和 clang++),您可以#warning用生成警告的内容替换该行。
例如,一个未使用的(可能有一个会说话的名字)变量。
我尝试过
template <typename State>
void callStateFunction(const State& state) {
if constexpr (false) {
state.method();
} else {
int method_not_implemented[sizeof(State)];
}
}
Run Code Online (Sandbox Code Playgroud)
并使用非方法值调用(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)];
| ^~~~~~~~~~~~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)
来自 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);
^
Run Code Online (Sandbox Code Playgroud)
来自 clang++(头 11.0.0)
我建议未使用的变量取决于模板类型名(State),否则,如果我将非因变量定义为
int method_not_implement;
Run Code Online (Sandbox Code Playgroud)
我收到 clang++ 的警告
prog.cc:7:9: warning: unused variable 'method_not_implemented' [-Wunused-variable]
int method_not_implemented;
^
Run Code Online (Sandbox Code Playgroud)
也无需使用非方法对象调用函数。
| 归档时间: |
|
| 查看次数: |
172 次 |
| 最近记录: |