c++ - 带有 const 限定符的类型推导失败

标签 c++ templates constants template-argument-deduction

在编写自定义迭代器类型时,我决定我希望能够从 const 迭代器转换为非 const 迭代器。我编写了以下 remove_const 函数。出于某种原因,编译器无法推断出 const Pconst int* 相同。我从 GCC 8.2 得到的错误是 types 'const P' and 'const int*' have incompatible cv-qualifiers

我的代码中是否存在阻止编译器正确推导的内容?此外,如果有更好的方法来做我想做的事情,我很想知道。

template <int, typename P>
struct my_iterator { P ptr; };

using iterator = my_iterator<3, int*>;
using const_iterator = my_iterator<3, const int*>;

template <int I, typename P>
my_iterator<I, P> remove_const(my_iterator<I, const P> it) {
    return my_iterator<I, P>{ const_cast<P>(it.ptr) };
}

int main() {
    const_iterator it{ nullptr };
    remove_const( it );
    return 0;
}

Here is a godbolt link with the code

最佳答案

对于 const Pconst 直接限定在 P 上,给定 Pint * const P 将是 int * const(即 const 指针),而不是 const int * (指向 const 的指针)。

您可以将代码更改为

template <int I, typename PtoC>
auto remove_const(my_iterator<I, PtoC> it) {
    using PtoNC = std::add_pointer_t<std::remove_const_t<std::remove_pointer_t<PtoC>>>;
    return my_iterator<I, PtoNC> { const_cast<PtoNC>(it.ptr) };
}

关于c++ - 带有 const 限定符的类型推导失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52237268/

相关文章:

c++ - 两个类可以同时互相继承吗?

c++ - <未解析的重载函数类型> 调用二元谓词

c++ - 对类型 '' 的非常量左值引用无法绑定(bind)到类型 ' *' 的临时对象

c++ - 在 QAbstractItemView 中查找拖放操作的结束

c++ - std::map 的单元测试

c++ - 根据不同条件初始化类模板的成员

C++ 模板样式,旨在更容易理解编译器错误消息

c# - 连接常量字符串和枚举

ruby-on-rails - 运行脚本/服务器时如何定义常量?

c++ - 运算符重载错误 "no match for operator error"