c++ - Const 在模板函数参数列表中被忽略

标签 c++ templates pointers visual-c++

我对模板类中的函数定义有疑问。

我有一个模板类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/

相关文章:

c++ - 将零分配给指针会破坏分配的内存吗?

c++ - Bruce Eckel 的 Thinking in C++ 中指向成员的指针

c++ - 如何将值从不同的多个数组传递到新的单个数组?

c++ - 用于分布式计算的 C/C++ 框架(MPI?)

c# - 如何在 C# 中映射双 C 结构指针?

c++:参数参数转换类的好名字

javascript - 如何让一个div出现,然后一直向右滑动,然后慢慢淡出?

c++ - 错误: request for member ‘prev_’ in something not a structure or union

c++ - 如何将类型的名称作为字符串嵌入到 static_assert() 中?

templates - AWS Cloudformation:Fn::Join 在 Fn::FindInMap 语句中?