C++模板中的条件语句,只能由编译器基于条件包含
Conditional statements in C++ template which could and must only be included by the compiler based on a condition
是否可以在C++模板中使用条件语句,如果条件为true,则只能"编译",否则无法保证"编译"(但编译器检测到它无论如何都不需要代码,因此无论如何都不会包含它)?
例如,由于模板实例化A
没有名为k
的成员,因此下面的代码不会编译。然而,这部分代码实际上是模板实例化A
的死代码。
(这个问题的实际用例:我想支持多个顶点类型来加载网格。根据顶点类型,网格文件中的某些信息将被跳过或不会被跳过,索引唯一顶点也会有所不同。)
#include <iostream>
struct A {
static constexpr bool value = false;
};
template < typename T >
inline bool f(const T &t) {
if (T::value) {
return t.k; // error: 'const struct A' has no member named 'k'
}
else {
return true;
}
}
int main() {
A a;
std::cout << f(a);
}
这里有两个选项。
你可以使用这样的模板专业化:
template < typename T >
inline bool f(const T &t) {
if (T::value) {
return t.k;
}
else {
return true;
}
}
template <>
inline bool f<A>(const A &t) {
return true;
}
你可以像这样使用if-constexpr
(C++17):
template < typename T >
inline bool f(const T &t) {
if constexpr (T::value) {
return t.k;
}
else {
return true;
}
}
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 在没有太多条件句的情况下,我如何避免被零除
- 基于多个条件处理地图中的所有元素
- 条件constexpr函数
- 无论条件是否为true,if总是在c++中执行
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 基于模板值的条件变量
- C++等效于 C# 的 "?." 空条件运算符
- 条件_variable和unique_lock如何适用于线程安全列表
- 如何避免参数数量依赖于条件的调用分支?
- 如何编写一个通用函数,该通用函数在没有任何条件和条件的情况下工作(无论是真实和错误)
- 如何将std::enable_if与一个本身取决于另一个条件的条件一起使用
- 如何有效地设计一种方法,使每个条件都依赖于另一个条件
- 将条件应用于整个向量
- 有条件地初始化一个结构体字段——仅当它存在于该结构体中时
- 条件预处理器相对于条件语句的优势
- 设置依赖于调用栈的条件断点
- 有条件地启用子类型(类似于启用函数的enable_if)
- C++:不应用于简单嵌套if-then-else语句的条件
- 计算类似于二项和的条件概率