好的,我通读了很多“无法推断模板参数”的问题,但似乎没有一个与我的情况相符——或者我不明白答案……</p>
我的标题中的精简代码如下所示:
template<typename T>
class TemplateProblem
{
public:
// Do I really need this or did I miss something from the STL?
template<typename Tin, typename Tout>
struct UnaryFunction : public std::unary_function<Tin, Tout>
{
virtual Tout operator()(Tin input) = 0;
};
template<typename Tin, typename Tout>
struct StaticCast : public UnaryFunction<Tin, Tout>
{
virtual Tout operator()(Tin input)
{
return static_cast<Tout>(input);
}
};
private:
T * const _data;
T const _bias;
template<typename Tin>
void Init(Tin * data, int length, UnaryFunction<Tin, T> mapper, Tin bias);
public:
template<typename Tin>
TemplateProblem(Tin * data, int length, Tin bias = Tin());
template<typename Tin>
TemplateProblem(Tin * data, int length, UnaryFunction<Tin, T> mapper, Tin bias = T());
};
template<typename T>
template<typename Tin>
void TemplateProblem<T>::Init(Tin * data, int length, UnaryFunction<Tin, T> mapper, Tin bias)
{
T mappedBias = mapper(bias);
for (int i = 0; i < length; i++)
{
_data[i] = data[i] + mappedBias;
}
}
template<typename T>
template<typename Tin>
TemplateProblem<T>::TemplateProblem(Tin * data, int length, UnaryFunction<Tin, T> mapper, Tin bias = T())
: _data(new T[length]), _bias(bias)
{
Init(data, length, mapper, bias);
}
template<typename T>
template<typename Tin>
TemplateProblem<T>::TemplateProblem(Tin * data, int length, Tin bias = T())
: _data(new T[length]), _bias(bias)
{
StaticCast<Tin, T> cast;
Init(data, length, cast, bias);
}
我这样实例化它:
unsigned char pixels[] = {23, 42, 65, 97};
TemplateProblem<int> tp(pixels, 4);
从 VS2012 我收到这些消息:
Error 1 error C2784: 'void TemplateProblem<T>::Init(Tin *,int,TemplateProblem<T>::UnaryFunction<Tin,T>,Tin)' : could not deduce template argument for 'TemplateProblem<T>::UnaryFunction<Tin,T>' from 'TemplateProblem<T>::StaticCast<Tin,Tout>' ...\templateproblem.h 62 1 TemplateProblem
Error 2 error C2893: Failed to specialize function template 'void TemplateProblem<T>::Init(Tin *,int,TemplateProblem<T>::UnaryFunction<Tin,T>,Tin)' ...\templateproblem.h 62 1 TemplateProblem
正如这个答案所暗示的,当我将两个struct
s 移出时,也会发生错误。class