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