あなたはできません:)あなたが望むのは、代わりにメンバー関数を特殊化することです:
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;
}
別の、もう少し複雑な解決策は、次を使用すること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;
}
これにより、任意の dim != 3 に対して cross_product が呼び出されると、コンパイル時エラーが発生します。「トリック」は、パラメーターを持つ関数に対してのみ機能することに注意してください。これは、テンプレート パラメーターを自動推定できるからです。パラメータのない場合、上記の関数を提供しましたwithout_parameters
:)。