Jump to content
  • Advertisement
Sign in to follow this  

"Friending" all instances of a template

This topic is 4724 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

In short: How do you friend a template (struct/class/union/function) so that all instances of that template becomes your friend? The long story: Consider the following code:
template <class T> struct Foo
{
   Foo(T& data) : m_data(data)
   {
   }
   template <class From> Foo(const Foo<From>& from) : m_data(from.m_data) // <= Compiler Error: from.m_data is inaccesible
   {
   }
private:
  friend struct Foo<????>; // How do you friend a complete subset?
  T m_data;
};

void
main(void)
{
  Foo<int> bar(1);
  Foo<float> foo(bar); // Since there exists an int=>float construct, I'd like this to work.
}


Share this post


Link to post
Share on other sites
Advertisement
This should work:

template <class T> struct Foo
{
Foo(T& data) : m_data(data)
{
}
template <class From> Foo(const Foo<From>& from) : m_data(from.m_data)
{
}
private:
template<class OtherT>
friend struct Foo; //Like this
T m_data;
};

int
main(void)
{
Foo<int> bar(1);
Foo<float> foo(bar); // Since there exists an int=>float construct, I'd like this to work.
}


Notes:

  • void main is not ISO C++; use int main. You can still miss out the return statement, as main() implicitly returns 0.
  • The 'OtherT' token is not necessary: you could use an anonymous template parameter
    template<class> friend struct Foo;

Share this post


Link to post
Share on other sites
I feel stupid, now it works!
I almost tried that: "template<class OtherT> friend struct Foo<OtherT>;"

I'm not using void main(void) in real life... just for the sample code, me being lazy :) (Actually it's not even a console app).

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!