Consider the following code:
template <int dim> struct vec { vec normalize(); }; template <> struct vec<3> { vec cross_product(const vec& second); vec normalize(); }; template <int dim> vec<dim> vec<dim>::normalize() { // code to normalize vector here return *this; } int main() { vec<3> direction; direction.normalize(); }
Compiling this code produces the following error:
1>main.obj : error LNK2019: unresolved external symbol ‘public: struct vec<3> __thiscall vec<3>::normalize(void)’ (?normalize@?$vec@$02@@QAE?AU1@XZ) referenced in function _main
You can’t 🙂 What you want is to specialize the member functions instead:
Another, slightly more complicated solution is to use
boost::enable_if:That will cause a compile time error if cross_product is called for any dim != 3. Note that that ‘trick’ only works for functions with parameters, since only then the template parameter can be auto-deduced. For cases without parameters, i have provided a function
without_parametersabove :).