I have a case in my code where I need to make a dependent template class a friend, but I think I've exhausted the possibilities and none of them work. Is this possible to do at all? If so, how?

Simplest example:

struct Traits {
    template <typename T>
    struct Foo {
        typedef typename T::bar* type;
    };
};

template <typename T>
class Bar
{
    typedef int bar;
    // need to make T::Foo<Bar> a friend somehow?
    typedef typename T::template Foo<Bar>::type type; // won't compile because bar is private... 
                                                      // suppose I cannot make bar public.


    type val;
};

int main() {
    Bar<Traits> b;
}
有帮助吗?

解决方案

struct Traits {
    template <typename T>
    struct Foo {
        typedef typename T::bar* type;
    };
};

template <typename T>
class Bar
{
    typedef int bar;
    friend typename T::template Foo<Bar>;
    typedef typename T::template Foo<Bar>::type type;
    type val;
};

int main() {
    Bar<Traits> b;
}

其他提示

Try something like

using my_friend=typename T::template Foo<Bar>;
friend my_friend;

inside your class (example)

I was able to get it to compile with this inserted at the point of your comment:

friend struct Traits::Foo<Bar>;

Honestly, wouldn't you be better off with something like this?

template <typename T>
class Bar;

struct Traits
{
public:
  template <typename T>
  struct Foo
  {
    typedef Bar<T> bar_type;
    typedef typename bar_type::bar* type;
  };
};

template <typename T>
class Bar
{
  typedef int bar;
  typedef Bar self_type;
  typedef struct Traits::template Foo<T> traits_type;

  friend traits_type;

  typedef typename traits_type::type type;

  type val;
};


int main(int argc,char** argv)
{
  Bar<Traits> b;
}

It is alot safer than allowing anything that contains a public typedef type to be your friend, though it is all...weird.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top