C++模板中的条件语句,只能由编译器基于条件包含

Conditional statements in C++ template which could and must only be included by the compiler based on a condition

本文关键字:条件 于条件 编译器 包含 语句 C++      更新时间:2023-10-16

是否可以在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;  
}
}