Note that there are some explanatory texts on larger screens.

plurals
  1. POCan you use an undefined type in a C++ template function if the function is never used?
    primarykey
    data
    text
    <p>I am trying to create a conversion function between objects of two classes (Eigen::Vector3d and MyVector, a Protocol Buffers message), but I want to delay evaluation of the function body until the function is referenced (at which point both classes would be defined).</p> <p>The function should be callable in files that later define both classes, and it should not cause a compilation error if the function is never used.</p> <p>I have:</p> <pre><code>#include &lt;Eigen/Core&gt; // defines Eigen::Vector3d class MyVector { public: int set_x(int x) { x_ = x; } private: int x_; } void operator&lt;&lt; (MyVector &amp;msg, const Eigen::Vector3d &amp;vec) { msg.set_x(vec.x()); } </code></pre> <p>which I use as:</p> <pre><code>MyVector msg; Eigen::Vector3d vec(1, 2, 3); msg &lt;&lt; vec; </code></pre> <p>This works fine if the function is defined after MyVector, but I would like to be able to define the function such that it can be included in a translation unit that lacks the MyVector class.</p> <p>I could change the function to this:</p> <pre><code>template&lt;typename Msg&gt; void operator&lt;&lt; (Msg &amp;msg, ... </code></pre> <p>but this is unacceptable because it would apply to other message classes:</p> <pre><code>quaternion_msg &lt;&lt; Eigen::Vector3d(1, 2, 3); // quaternion has xyz but also w! </code></pre> <p>and I want that to cause a build error.</p> <p>Is there some kind of template magic that can do that? If not, is there a better way to provide this operator short of adding MyVector to the header file (or its dependencies)?</p>
    singulars
    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.
 

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