【问题标题】:Use concepts to check if a global function exists使用概念检查是否存在全局函数
【发布时间】:2020-10-11 19:19:30
【问题描述】:

我可以创建一个概念来检查是否存在名为 to_string() 的成员函数,该函数在结构/类中返回 std::string。

template<typename T>
concept method_to_string = requires(T v)
{
    { v.to_string() } -> std::same_as<std::string>;
};

我想创建一个概念来检查是否存在名为 to_string 的全局函数,该函数接受 T,并返回 std::string。我做不到。我使用 gcc 10.2 作为编译器。

我的猜测是我会看起来像这样,但它失败了:

template<typename T>
concept function_to_string = requires(T v)
{
    to_string(const T&) -> std::same_as<std::string>;
};

【问题讨论】:

标签: c++ c++20 c++-concepts


【解决方案1】:

这似乎有效:

template<typename T>
concept method_to_string = requires(T v)
{
    { to_string(v) } -> std::same_as<std::string>;
};

https://gcc.godbolt.org/z/7WdTjf

【讨论】:

  • 是的,那个有效。需要解决的是另一个概念。
  • @mlom 我不确定您指的是什么其他概念:“我想创建一个概念来检查是否存在一个名为 to_string 的全局函数,该函数接受一个 T,并返回一个 std::string ”。 { to_string(v) } 部分检查全局函数。
  • @mlom 好的,不用担心 :)
猜你喜欢
  • 2016-11-16
  • 1970-01-01
  • 1970-01-01
  • 2018-07-07
  • 2021-09-15
  • 2020-09-11
  • 1970-01-01
  • 1970-01-01
  • 2020-06-11
相关资源
最近更新 更多