我对模板类中的函数定义有疑问。
我有一个模板类Array
,它有一个成员函数IndexOf
:
// Defined in header
template <typename T>
class Array {
// Other stuff
int IndexOf(const T value) const {
// Code of function
};
// Other stuff
};
当我使用类指针创建数组实例时,函数忽略 const T
并仅使用T
。因此,当我使用 const T
调用该函数时,出现编译器错误:“没有重载函数的实例”:
#include "Array.h"
class Object{
// Object stuff
};
int main(){
// Demonstration code
Array<Object*> objects = Array<Object*>(); // Array of Object*
Object* obj = new Object(); // An Object*
const Object* cobj = new Object(); // A const Object*
// This works fine
objects.IndexOf(obj); // No problems
// This has compile error
objects.IndexOf(cobj); // No idea why
delete obj;
delete cobj;
return 0;
}
代码似乎忘记函数的参数是const T
。函数参数应该是const Object*
,但它把参数当作只是Object*
。
知道为什么会这样吗?
如果我没有使用指针作为类型,则不会发生错误。
函数内部的代码不会引起问题。
之前说过,不,我不会使用 std::vector
或其他类似的东西来动态调整数组大小。这会带走所有的乐趣。
最佳答案
实际上你的函数声明可以看作是:
IndexOf(const (Object *) val)
这基本上意味着 Object *
应该指向 const 对象,如下所示:
Object *const cobj = new Object();
现在您将拥有正确的行为。 但是,如果您真的对 const 指针感兴趣,那么您需要将声明修改为:
Array<const Object *> objects;
关于c++ - Const 在模板函数参数列表中被忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50068728/