具有类似 friend 访问权限的 C++ 概念

标签 c++ friend c++17 c++-concepts

是否可以让这段代码按照我的意愿工作? IE。允许概念访问私有(private)成员函数?

template <typename T>
concept bool Writeable()
  { return requires (T x,std::ostream os) { { x.Write(os) } -> void }; }

template <Writeable T>
void Write(std::ostream &os,const T &x) { x.Write(os); }

class TT
{
private:
  void Write(std::ostream &os) const { os << "foo"; }

//friend concept bool Writeable<TT>();
friend void ::Write<TT>(std::ostream &,const TT &);
};

谢谢

最佳答案

没有。明确不允许概念成为 friend 。

n4377 7.1.7/2

Every concept definition is implicitly defined to be a constexpr declaration (7.1.5). A concept definition shall not be declared with the thread_local, inline, friend, or constexpr specifiers, nor shall a concept definition have associated constraints (14.10.2).

我们可以将其缩减为这个示例,以表明访问确实是问题所在:

template <typename T>
concept bool Fooable = requires (T t) { { t.f() } -> void };

struct Foo
{
private:
    void f() {}
};


int main()
{
    static_assert(Fooable<Foo>, "Fails if private");
}

但是你可以使用一个间接级别,像这样:

template <typename T>
void bar(T t) { t.f(); }

template <typename T>
concept bool FooableFriend = requires(T t) { { bar(t) } -> void };

struct Foo
{
private:
    void f() {}

    template<typename T>
    friend void bar(T t);
};


int main()
{
    static_assert(FooableFriend<Foo>, "");
}

Live demo incorporating your example

哪个有效。概念还很早,所以我想象他们可能会取消 friend 限制,就像过去提案取消对 C++11/14 功能的限制一样。

关于具有类似 friend 访问权限的 C++ 概念,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37295690/

相关文章:

C++ 如何正确地将 const float 舍入为 unsigned int

c++ - 跨平台和语言插件系统

c++ - 友元声明的复杂范围规则有什么意义?

C++ 模板特化友元迭代器错误 : invalid use of incomplete type

c++ - 使用带有可变参数模板结构的 std::visit

c++ - 如何编写可以迭代泛型类型的函数

c++ - 保留字典顺序的原始类型的字符串编码

c++ - 从 Stroustrup 的 C++ 编译模板友元示例时出现问题

c++ - 函数模板不适用于字符串文字

c++ - 使用 <experimental/filesystem> 和调用函数的链接器错误