Question

The Y:

I'm going to doubt it because the classes (technically) have no relationship, but is there any way that I can make classes with other template implementations friends?

The X:

I'm playing around with making my own fixed point class for pedagogical reasons. The only reason anyone whould ever need to get the underlying fixed point value would be when building a fixed point from another fixed point, eg

template <typename I, size_t R>
class FixedPoint
{
public:
  template <typename J, size_t Rj>
  FixedPoint(const FixedPoint<J,Rj>& ref)
  {
        ...
     std::ptrdiff_t radix_diff = R-Rj;
     val_ = ref.val_ >> radix_diff;//there is more to this but you get the idea
  }
private:
  I val_;
}

So basically, I'd really like to make the following true:

template <typename J,typename Rj>
friend FixedPoint<J,Rj>::FixedPoint(const FixedPoint<I,R>& ref);

Though obviously that's not possible. Is there any way to do this other than making a getter function to val_ public?

Edit:

I'm going to add that I'm not actually sure if this isn't possible, in g++ i get the "Internal Compiler Error":

/home/user/source/testdir/main.cpp: In instantiation of 'class FixedPoint<signed char, 4ul>':
/home/user/source/testdir/main.cpp:115:24:   required from here
/home/user/source/testdir/main.cpp:64:10: internal compiler error: unexpected expression 'Rj' of kind template_parm_index
   friend FixedPoint<J,Rj>::FixedPoint(const FixedPoint<I,R>& ref);
          ^
Please submit a full bug report,
with preprocessed source if appropriate.
See <http://bugzilla.redhat.com/bugzilla> for instructions.
Preprocessed source stored into /tmp/ccWaztkQ.out file, please attach this to your bugreport.
make[2]: *** [CMakeFiles/TestProgram.dir/main.cpp.o] Error 1
make[1]: *** [CMakeFiles/TestProgram.dir/all] Error 2
make: *** [all] Error 2
15:17:06: The process "/usr/bin/make" exited with code 2.
Error while building/deploying project TestProgram (kit: Desktop)
When executing step 'Make'
Was it helpful?

Solution

Clang 3.5 does not give an internal error, but also does not let you instantiate a template inside the template definition (it's possible that this is an infinite loop). So, the answer is

template<typename,typename> friend class FixedPoint;

To make all instances of the template friends with each other... :(

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top