gpt4 book ai didi

c++ - 如何使用概念来约束可变参数函数的参数类型?

转载 作者:行者123 更新时间:2023-12-02 18:02:07 25 4
gpt4 key购买 nike

我有一个可变参数函数,它可以接受输入参数的任意组合,只要这些参数中的每一个都可以转换为 bool。 :

#include <concepts>
#include <cstddef>

// internal helper functions
namespace {
template <typename T>
constexpr std::size_t count_truths(T t) {
return (bool)t;
}

template <typename T, typename... Args>
constexpr std::size_t count_truths(T t, Args... args) { // recursive variadic function
return count_truths(t) + count_truths(args...);
}
}

template <typename T>
concept Booly = std::convertible_to<T, bool>;

// variadic function for which all arguments should be constrained to Booly<T>
// e.g. only_one(true, false, true, false, true) = false; only_one(true, false) = true
template <typename T, typename... Args> requires Booly<T>
constexpr bool only_one(T t, Args... args) {
return count_truths(t, args...) == 1;
}

我试图使用概念来限制模板只允许传递 bool 可转换类型,但我只设法对第一个参数这样做:

// following lines compile:
only_one(true, false, false);
only_one(BoolConvertible(), true, false);

// this line is correctly forced to failure due to the concept not being satisfied:
only_one(NonBoolConvertible(), false, true);

// BUT this line is not detected as a concept constraint failure (but still compilation failure):
only_one(true, NonBoolConvertible(), false, true);

我如何使用 C++20 概念来约束剩余的模板参数以确保它们中的每一个都在 Args... 中满足Booly<>

最佳答案

你可以展开Args通过(Booly<Args> && ...)将每个单独的类型传递给 Booly .用 && 链接结果因此只会产生 true如果所有类型都满足 Booly .

template <typename T, typename... Args> requires Booly<T> && (Booly<Args> && ...)
constexpr bool only_one(T t, Args... args) {
return count_truths(t, args...) == 1;
}

Demo :

struct foo {
operator bool();
};
struct bar {};

int main() {
only_one(true, true, false);
only_one(foo{}, true);
only_one(bar{}, true); //C2672
only_one(true, bar{}); //C2672
}

关于c++ - 如何使用概念来约束可变参数函数的参数类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74156130/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com