C++20 概念 如何定义带有参数的函数的存在?

C++20 concepts how to define existence of a function with arguments?

本文关键字:参数 函数 存在 概念 何定义 定义 C++20      更新时间:2023-10-16

在C++20中,我们现在可以使用概念而不是SFINAE来确定模板类型名中是否存在函数:

template<typename T> concept fooable = requires (T a) {
a.foo();
};
class Foo {
public:
// If commented out, will fail compilation.
void foo() {}
void bar() {}
};
template <typename T> requires fooable<T>
void foo_it(T t) {
t.bar();
}
int main()
{
foo_it(Foo());
}

我们如何对具有非空参数的函数执行此操作?

您可能在requires中有额外的参数:

template<typename T> concept fooable = requires (T a, int i) {
a.foo(i);
};

演示

最好的选择似乎是declval

template<typename T> concept fooable = requires (T a) {
a.foo(std::declval<int>());
};
class Foo {
public:
void foo(int x) {}
void bar() {}
};
template <typename T> requires fooable<T>
void foo_it(T t) {
t.bar();
}
int main()
{
foo_it(Foo());
}