5

如果这个问题的标题没有帮助,我深表歉意;如果不给出以下示例,我不知道如何简洁地提出这个问题:

template <template <class> class Arg>
class C {
    typedef C<Arg> type;
    friend class Arg<type>;
  public:
    C() {
        a_.set(this);
    }
  private:
    int i_;
    Arg<type> a_;
};

template <class Type>
class Arg1 {
  public:
    void set(Type* t) {
        t_ = t;
        t_->i_ = 1;
    }
  private:
    Type* t_;
};

namespace NS {

    template <class Type>
    class Arg2 {
      public:
        void set(Type* t) {
            t_ = t;
            t_->i_ = 2;
        }
      private:
        Type* t_;
    };

}

如您所见,Arg2Arg1. 但是,VS 2008 只允许Arg1用作模板参数:

int main() {
    C<Arg1> c1; // compiles ok
    C<NS::Arg2> c2; // error C2248

    return 0;
}

错误是'C<Arg>::i_' : cannot access private member declared in class 'C<Arg>'i_如果公开,一切正常,所以这似乎是一个友谊问题。

当模板模板参数位于不同的命名空间时,导致友谊声明失败的原因是什么?

4

1 回答 1

0

命名空间成员资格不影响友谊的资格。这是一个编译器错误。

friend and namespace are language features that interact, though, so it's not particularly surprising as bugs go. Perhaps it's actually friending a nonsense forward declaration in the enclosing namespace, ::Arg2<type>.

于 2013-02-26T03:57:09.000 回答