有人知道如何制作C ++概念T
,以便如果存在{的重载,则仅为类型为g
的参数t
定义函数T
f
中的{1}}接受参数B
?
t
例如,我想为struct A1 {};
struct A2 {};
struct B {
void f(A1 a1) {}
};
void g(T t) {
B b;
b.f(t);
}
接受的所有内容定义一个to_string
,并定义类似的内容
std::stringstream
关于概念的所有示例都处理了要求在一个类型上存在一个函数的较简单情况,而在这种情况下,我们要检查另一个类型上一个函数的存在。
答案 0 :(得分:5)
如果要检查类型是否可流式传输,可以使用类似以下内容的
#include <iostream>
#include <concepts>
#include <sstream>
template <typename T>
concept Streamable = requires (T x, std::ostream &os) { os << x; };
struct Foo {};
struct Bar {};
std::ostream& operator<<(std::ostream& os, Foo const& obj) {
// write obj to stream
return os;
}
template <Streamable T>
std::string to_string(T t) {
std::stringstream ret;
ret << t;
return ret.str();
}
int main() {
Foo f;
Bar b;
to_string(f);
to_string(b); // error
return 0;
}
答案 1 :(得分:2)
您可以在一个概念中使用两个不同的 type 占位符,以要求存在其中一个类型占位符的实例的成员函数,以及所述成员函数的参数匹配其他占位符的类型。例如:
code=H82 desc="Free app running time quota exhausted"