Consider the following template class:
template <typename T> class Function {
public:
virtual float eval( const T &x, const T &y ) = 0;
};
因为'eval'函数不应该修改两个输入值'x'和'y'的值,所以我将它们设为“const”。 然后我创建了以下从Function派生的类。
class Foo1 : public Function <float*> {
public:
Foo1() : Function <float*> () {}
virtual float eval( const float* &x, const float* &y ) { ... }
};
当我使用g++编译时,我收到以下警告:
hidden overloaded virtual function 'Function<float *>::eval' declared here: type mismatch at 1st parameter
('float *const &' vs 'const float *&')
virtual float eval( const T &x, const T &y ) = 0;
我无法实例化Foo1类。编译器报错说函数“eval”未实现。 为了让编译器满意,派生类必须如下所示:
class Foo2 : public Function <float*> {
public:
Foo2() : Function <float*> () {}
virtual float eval( float* const &x, float* const &y ) { ... }
};
Foo2::eval函数使用了两个类型为'float * const'的参数,而不是'const float *'。换句话说,Foo2::eval可以修改数组'x'和'y'的内容,这不是我想要的。
我尝试将模板类'Function'更改如下:
virtual float eval( T const &x, T const &y ) = 0;
但是类Foo1仍然无法工作,而类Foo2与之前的情况相同。
- 因此看起来模板类中的'const T &x'或'T const &x'都意味着派生类中的'float * const & x'。这是正确的吗? - 如果我想在派生类中使用'const float * & x'(或'const float * x'),我的模板类Function应该是什么?
谢谢。