gpt4 book ai didi

c++ - 将 const this 传递给接受 const 指针的函数不是 const 正确的吗?

转载 作者:搜寻专家 更新时间:2023-10-31 00:31:03 25 4
gpt4 key购买 nike

我有一个类模板 Foo具有以下成员函数:

bool contains(const T& item) const

我已经用指针类型实例化了它:Foo<Bar*> ,让我期望成员函数现在将具有以下签名:

bool contains(const Bar*& item) const

constBar成员函数,我尝试传递 thisFoo<Bar*>::contains :

bool Bar::func(const Foo<Bar*>& foo) const
{
return foo.contains(this);
}

编译失败,错误如下:

error: invalid conversion from ‘const Bar*’ to ‘Bar*

问题:

  • 为什么我的const T&参数不正确?
  • Foo<T>::contains(...) const 的签名是什么?需要允许使用 this 调用编译?

完整示例:

#include <vector>
#include <algorithm>

template<typename T>
struct Foo
{
bool contains(const T& item) const
{
return false;
}
};

struct Bar
{
bool func(const Foo<Bar*>& foo) const
{
return foo.contains(this);
}
};

错误输出:

scratch/main.cpp:17:33: error: invalid conversion from ‘const Bar*’ to ‘Bar*’ [-fpermissive]
return foo.contains(this);
^
scratch/main.cpp:7:10: note: initializing argument 1 of ‘bool Foo<T>::contains(const T&) const [with T = Bar*]’
bool contains(const T& item) const

最佳答案

I have instantiated this with a pointer type: Foo<Bar*>, leading me to expect that the member function will now have the following signature:

bool contains(const Bar*& item) const

这就是问题所在。当T = Bar* , 表达式

bool contains(const T& item) const

实际上会编译成

bool contains(Bar * const & item) const

也就是说,对 Bar 的常量指针的引用。考虑一下它是有道理的:您希望 T 是 const,然后您想要对它的引用。

如果您想以通常的“预期”方式应用常量(尽管这可能会给经验丰富的 C++ 程序员带来一些意外),您可以按以下方式声明您的容器和成员函数:

template <class T>
class Container {
public:
using const_bare_type = typename std::conditional<
std::is_pointer<T>::value,
typename std::remove_pointer<T>::type const*,
const T>::type;

bool contains(const const_bare_type& item);
};

关于c++ - 将 const this 传递给接受 const 指针的函数不是 const 正确的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35000747/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com