Tik*_*454 2 c++ templates c++-concepts c++20
我有一个检查类型是否可迭代的概念
template<typename T>
concept Iterable = requires(T t) {
    t.begin();
};
由于重载问题,我无法在模板中使用它,所以我想做类似于以下的操作:
template<typename T>
void universal_function(T x) {
    if (x is Iterable)
        // something which works with iterables
    else if (x is Printable)
       // another thing
    else
       // third thing
}
概念实例化是布尔值,因此它们可以在语句中使用if。您将需要使用它if constexpr来实现所需的行为,因为它将允许包含在不同分支中无效的代码的分支:
if constexpr (Iterable<T>) {
    // ...
} else if constexpr (Printable<T>) {
    // ...
} else {
    // ...
}