-
template specialization
I wanted to specify two very, very similar classes without having to write them out twice. However, when I specify member functions of one of the two possible cases, the compiler complains that the type I'm referring to is incomplete. What am I missing in this method? (stripped down)
Code:
template<class unary_func, bool Kd_weighted = false>
class sum : public func2d
{
public:
void operator()(grid::size_type x, grid::size_type y, grid::base_type & g, grid::data_type Kd = 1.0);
private:
grid::data_type s;
unary_func f;
};
template<class unary_func>
void sum<unary_func,false>::operator()(grid::size_type x, grid::size_type y, grid::base_type & g, grid::data_type Kd)
{
s += f( g(x,y) );
}
template<class unary_func>
void sum<unary_func,true>::operator()(grid::size_type x, grid::size_type y, grid::base_type & g, grid::data_type Kd)
{
s += Kd * f( g(x,y) );
}
Code:
error: invalid use of incomplete type ‘class functions::sum<unary_func, false>’|
error: declaration of ‘class functions::sum<unary_func, false>’|
error: invalid use of incomplete type ‘class functions::sum<unary_func, true>’|
error: declaration of ‘class functions::sum<unary_func, true>’|
Thanks.
*edit* Of course the classes are incomplete, but won't they be written at compile time, since I'm using them? Does the 'bool' not limit us to only two possibilities for a given unary_func?
-
You can't specialize a member function of a class template. You have to specialize the class template itself.
gg
-
Well would you look at that.
Thanks.
-
It might look something like that:
Code:
template <bool Kd_weighted>
struct summer {};
template <>
struct summer<true>
{
template <class unary_func>
grid::data_type operator()(grid::size_type x, grid::size_type y, grid::base_type& g, grid::data_type Kd, unary_func f)
{
return Kd * f( g(x, y) );
}
};
template <>
struct summer<false>
{
template <class unary_func>
grid::data_type operator()(grid::size_type x, grid::size_type y, grid::base_type& g, grid::data_type, unary_func f)
{
return f( g(x, y) );
}
};
template<class unary_func, bool Kd_weighted>
void sum<unary_func,Kd_weighted>::operator()(grid::size_type x, grid::size_type y, grid::base_type & g, grid::data_type Kd)
{
s += summer<Kd_weighted>()(x, y, g, Kd, f);
}