8

是否可以使此代码按我的意愿工作?即允许概念访问私有成员函数?

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 &);
};

谢谢

4

1 回答 1

4

不可以。明确的概念不允许成为朋友。

n4377 7.1.7/2

每个概念定义都被隐式定义为 constexpr 声明(7.1.5)。概念定义不应使用 thread_local、inline、friend 或 constexpr 说明符声明,概念定义也不应具有关联的约束 (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>, "");
}

包含您的示例的现场演示

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

于 2016-05-18T10:40:20.413 回答