C ++-如何在模板类型上实施常量性?

问题描述 投票:1回答:1
template<typename T> struct SomeClass{

    void someFunc(const T& data) const {}

};

void testFunc(const int* a) {

    SomeClass<int*> some_class;

    some_class.someFunc( a);

}

我制作了一个具有非const类型的模板实例。现在,当调用某个函数时,出现以下错误:

error: invalid conversion from ‘const int*’ to ‘int*’
note: initializing argument 1 of ‘void SomeClass<T>::someFunc(const T&) const [with T = int*]’

因此,基本上我的const T&被视为普通T&const被忽略。为什么?在这种情况下,如何确保编译器将其视为const T&

c++ templates const
1个回答
0
投票

您需要将定义更改为SomeClass<const int*> some_class;T来自定义,为int*,编译器在正确地抱怨。

© www.soinside.com 2019 - 2024. All rights reserved.