【问题标题】:Type deduction with const qualifiers failingconst 限定符失败的类型推导
【发布时间】:2018-09-08 16:36:09
【问题描述】:

在编写自定义迭代器类型时,我决定希望能够从 const 迭代器转换为非 const 迭代器。我写了以下remove_const 函数。由于某种原因,编译器无法推断出const P 与const 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 int* 是 (const int)*,而不是 const (int*)。

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


【解决方案1】:

对于const P,const 直接限定在P 上,给定P 是int *,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) };
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-28
    • 1970-01-01
    • 2012-12-23
    • 1970-01-01
    • 1970-01-01
    • 2022-11-16
    • 1970-01-01
    • 2016-02-15
    相关资源
    最近更新 更多