如何将概念应用到概念中的成员函数然后使用?

问题描述 投票:0回答:1

这个问题的后续问题,其中单个参数的使用没有解决。

假设以下 C++ 概念:

template <typename T>
concept has_set = requires(T t, std::string s) {
    { t.set(s) } -> std::same_as<void>; };
};

我无法使用参数

s
的概念,例如

template <typename T>
concept has_set = requires(T t, std::convertible_to<std::string_view> s) {
    { t.set(s) } -> std::same_as<void>; };
};

将无法编译。是否有任何解决方法或技巧可以在这里应用以让以下附加代码编译?

std::string use(has_set auto & f) { /* ... use f.set(...) ... */ }

请注意,部分解决方案已在 https://stackoverflow.com/a/79130496/1528210

中给出
c++ c++-concepts
1个回答
0
投票

这是对此处后续问题的答案的改编:

与其他情况类似,您可以向概念添加另一个模板参数,并要求其可转换为

std::string_view

为了允许按照您指定的方式使用它(无需提供额外的模板参数),第二个模板参数具有默认值

std::string
:

#include <type_traits>
#include <string_view>
#include <string>

template <typename T, typename S = std::string>
concept has_set = requires(T t, S s) {
    requires std::convertible_to<S, std::string_view>;
    { t.set(s) } -> std::same_as<void>;
};

使用示例:

struct HasSetClass
{
    void set([[maybe_unused]] std::string const & s) {}
};

void use(has_set auto & o)
{
     o.set("aaa");
}

int main() {
    HasSetClass a;
    use(a);
}

现场演示

© www.soinside.com 2019 - 2024. All rights reserved.