【问题标题】:Access private members in requires clause在 requires 子句中访问私有成员
【发布时间】: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


    【解决方案1】:

    当您为函数或函数模板添加好友时,只有该函数的主体才能获得访问权限,而不是其各种附件。附加到它的约束是无关的。

    您可以通过将检查移动到 f2 的正文中来解决此问题,以便在具有此访问权限的上下文中检查它:

    template <typename T>
    void f2(T& v)
    {
        if constexpr (requires { v.g(); }) {
            std::cout << "f2: can call g\n";
            v.g();
        } else {
            std::cout << "f2: cannot call g\n";
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-28
      • 2012-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 2011-07-27
      相关资源
      最近更新 更多