请考虑以下代码:
templatestruct vec { vec normalize(); }; template <> struct vec<3> { vec cross_product(const vec& second); vec normalize(); }; template vec vec ::normalize() { // code to normalize vector here return *this; } int main() { vec<3> direction; direction.normalize(); }
编译此代码会产生以下错误:
1> main.obj:错误LNK2019:未解析的外部符号"public:struct vec <3> __thiscall vec <3> :: normalize(void)"(?normalize @?$ vec @ $ 02 @@ QAE?AU1 @ XZ)引用在函数_main中
Johannes Sch.. 9
你不能:)你想要的是专门化成员函数:
templatestruct vec { // leave the function undefined for everything except dim==3 vec cross_product(const vec& second); vec normalize(); }; template<> vec<3> vec<3>::cross_product(const vec& second) { // ... } template vec vec ::normalize() { // code to normalize vector here return *this; }
另一个稍微复杂的解决方案是使用boost::enable_if
:
templatestruct vec { // function can't be called for dim != 3. Error at compile-time template typename boost::enable_if_c< dim == dim1 && dim1 == 3, vec >::type cross_product(const vec & second) { // ... } vec normalize(); // delegate to the template version void without_params() { // delegate this->without_params (); } private: // function can't be called for dim != 3. Error at compile-time template typename boost::enable_if_c< dim == dim1 && dim1 == 3 >::type without_params() { // ... } }; template vec vec ::normalize() { // code to normalize vector here return *this; }
如果为任何dim调用cross_product,那将导致编译时错误!= 3.请注意,'trick'仅适用于带参数的函数,因为只有这样才能自动推导出模板参数.对于没有参数的情况,我提供了without_parameters
上面的函数:).
你不能:)你想要的是专门化成员函数:
templatestruct vec { // leave the function undefined for everything except dim==3 vec cross_product(const vec& second); vec normalize(); }; template<> vec<3> vec<3>::cross_product(const vec& second) { // ... } template vec vec ::normalize() { // code to normalize vector here return *this; }
另一个稍微复杂的解决方案是使用boost::enable_if
:
templatestruct vec { // function can't be called for dim != 3. Error at compile-time template typename boost::enable_if_c< dim == dim1 && dim1 == 3, vec >::type cross_product(const vec & second) { // ... } vec normalize(); // delegate to the template version void without_params() { // delegate this->without_params (); } private: // function can't be called for dim != 3. Error at compile-time template typename boost::enable_if_c< dim == dim1 && dim1 == 3 >::type without_params() { // ... } }; template vec vec ::normalize() { // code to normalize vector here return *this; }
如果为任何dim调用cross_product,那将导致编译时错误!= 3.请注意,'trick'仅适用于带参数的函数,因为只有这样才能自动推导出模板参数.对于没有参数的情况,我提供了without_parameters
上面的函数:).