【发布时间】:2021-03-29 19:40:24
【问题描述】:
考虑以下程序:
#include <iostream>
template<typename T> void f1(T& v)
{
std::cout << "f1: can call g" << std::endl;
v.g();
}
template<typename T> void f2(T& v) requires requires (T& v) { v.g(); }
{
std::cout << "f2: can call g" << std::endl;
v.g();
}
template<typename T> void f2(T&) requires (!requires (T& v) { v.g(); })
{
std::cout << "f2: cannot call g" << std::endl;
}
class A
{
public: // if commented out, f2 will not call g anymore
void g()
{
std::cout << "g called" << std::endl;
}
template<typename T> friend void f1(T& v);
template<typename T> friend void f2(T& v);
};
class B
{
};
int main()
{
std::cout << "A" << std::endl;
A a{};
f1(a);
f2(a);
std::cout << "B" << std::endl;
B b{};
f2(b);
return 0;
}
函数g 可能存在于一个类中,也可能不存在。如果是(如A),则函数f2 应该调用它,如果不是(如B)则不应该调用它。这种区别是通过requires 子句进行的。
我在A 中与f2 成为朋友,因此即使它是私人的,它也应该能够调用g(一般而言,交朋友工作正常,请参阅f1)。但是,requires 似乎忽略了该函数已成为朋友,因此,当在 A 中将 g 设为私有时,g 不再被调用。
这是为什么?是否有解决方法,即决定是否可以调用函数,即使它是私有的(但已成为朋友)?也许甚至使用老派std::enable_if?
【问题讨论】:
标签: c++ c++20 c++-concepts