Note that there are some explanatory texts on larger screens.

plurals
  1. POIs it possible to narrow the friend relationship between classes and functions when multiple template types are involved?
    primarykey
    data
    text
    <p>Suppose I represent an image class as:</p> <pre><code>template &lt;typename Pixel&gt; class Image { ... }; </code></pre> <p>I would need my own swap function to prevent extra copying of images, so I would need to make it a friend of Image. If inside Image I write:</p> <pre><code>template &lt;typename T&gt; friend void swap(Image&lt;T&gt;&amp;, Image&lt;T&gt;&amp;); </code></pre> <p>I get what I want, but it makes all swap functions friends of all Image classes. So I can narrow the friend relationship as follows:</p> <pre><code>template &lt;typename Pixel&gt; class Image; template &lt;typename T&gt; void swap(Image&lt;T&gt;&amp;, Image&lt;T&gt;&amp;); template &lt;typename Pixel&gt; class Image { ... friend void swap&lt;&gt;(Image&amp;, Image&amp;); }; </code></pre> <p>as described in <a href="http://www.parashift.com/c++-faq-lite/templates.html#faq-35.16" rel="nofollow noreferrer">C++ FAQ-lite 35.16</a>.</p> <p>Now suppose I also have a convolution function that can take floating-point or integral kernels:</p> <pre><code>template &lt;typename Pixel, typename KernelValue&gt; Image&lt;Pixel&gt; convolve(const Image&lt;Pixel&gt;&amp;, const Kernel&lt;KernelValue&gt;&amp;); </code></pre> <p>Convolution needs access to Image's raw memory, so it too must be a friend. However, I would like to <em>partially narrow</em> the friendship so that convolve is a friend for all KernelValues but only the particular Pixel type, something like:</p> <pre><code>template &lt;typename KernelValue&gt; friend Image&lt;Pixel&gt; convolve(const Image&lt;Pixel&gt;&amp;, const Kernel&lt;KernelValue&gt;&amp;); </code></pre> <p>inside the Image definition. The compiler does not like this (or other variants) at all, mainly because it doesn't match the original function declaration, so the private pointer can't be accessed. Is it possible to get what I want here, or should I settle for the "more friendly" version?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload