模板类不接受const类型作为函数参数

时间:2020-10-31 10:56:00

标签: c++ templates

如果我创建一个函数,该函数接受两个参数,且两个参数均具有相同的模板类型,则其中之一为const。它不会与以下错误消息一起编译,这使我非常困惑,因为b和Input2应该都是const。

[build] ../main.cpp:26:27: error: cannot initialize a parameter of type 'int *' with an lvalue of type 'const int *'
[build]     object.DoSomething(a, b);
[build]                           ^
[build] ../main.cpp:10:46: note: passing argument to parameter 'Input2' here
[build]     void DoSomething(Type Input1, const Type Input2

这是我的代码示例:

template<class Type>
class A {
public:
    void DoSomething(Type Input1, const Type Input2) { ;}
};

int main(int, char**) {
    A<int*> object;
    int* a = new int(1); 
    const int* b = new int(2); 
    object.DoSomething(a, b);
}

如果我使用这样定义DoSomething函数,则一切正常:

    void DoSomething(Type Input1, const int* Input2) {;}

可悲的是,这对我没有帮助。

谢谢您的输入!

0 个答案:

没有答案