相关疑难解决方法(0)

if constexpr 中的 requires 子句问题

同时努力实现if constexprrequires clause基于如果constexpr和要求,表达了即席概念检查面临着以下问题:

template<class P>
concept TuplePair = requires(P p) {
    requires std::tuple_size<P>::value == 2;
    std::get<0>(p);
    std::get<1>(p);
};

void print(const auto& p) {
    if constexpr( TuplePair<decltype(p)> ) {
        std::cout << std::get<0>(p) << ", " << std::get<1>(p) << std::endl;
    }
    else {
        std::cout << "else" << std::endl;
    }
}

int main() {
    // justifiably prints 'else':
    print(std::make_tuple(3, 4, 5));

    // prints 'else' even though this is a valid TuplePair:
    print(std::make_tuple(1, 2));
}
Run Code Online (Sandbox Code Playgroud)

有什么问题if constexpr …

c++ c++-concepts c++20 if-constexpr

4
推荐指数
1
解决办法
227
查看次数

要求约束必须评估为 bool。所以没有 SFINAE

我对“原子约束”一章很好奇https://en.cppreference.com/w/cpp/language/constraints

它说

替换后 E 的类型必须恰好是 bool。不允许转换

f(0); // error: S<int>{} does not have type bool when checking #1,
          // even though #2 is a better match
Run Code Online (Sandbox Code Playgroud)

哎哟。这意味着在使用 require 子句时没有 SFINAE 机制?这不是很糟糕吗
因为我可以看到某些模板类型在遍历表达式后如何结果为 bool,但其他模板类型却看不到。现在我们又需要使用enable_if和东西了。痛得多?

c++ c++-concepts c++20

2
推荐指数
1
解决办法
775
查看次数

标签 统计

c++ ×2

c++-concepts ×2

c++20 ×2

if-constexpr ×1