【问题标题】:Calling wrong template function prototype problem in c++c++中调用错误的模板函数原型问题
【发布时间】:2020-05-01 20:29:14
【问题描述】:

我目前正在制作我的自定义矢量容器,以便更好地了解真正的 STL 容器。我面临“插入”功能的问题。

这是我的向量容器中“插入”的两个原型。

// 1
template <typename T, typename Alloc>
void vector<T, Alloc>::insert(iterator position, size_type n, const value_type &val)

// 2
template <typename T, typename Alloc>
template <class InputIterator>
void vector<T, Alloc>::insert(iterator position, InputIterator first, InputIterator last)

当我尝试在 main.cpp 中使用插入函数时,如下所示,

int main() {
    ft::vector<int> my;
    my.insert(my.begin(), 5, 6); <-- it calls second proto.
    return (0);
}

我打算调用第一个原型,但它调用了第二个用于迭代器参数的原型...... 你能解释一下它为什么会发生以及如何解决它吗?

【问题讨论】:

    标签: c++ templates


    【解决方案1】:

    您需要使用一些 SFINAE 将 InputIterator 重载限制为迭代器类型。

    假设您的迭代器遵循 iterator_traits 和/或具有像 iterator_category 这样的嵌套类型,您可以通过 SFINAE 检查它的存在:

    template <class Iter>
    using iter_cat_t = typename iterator_traits<Iter>::iterator_category;
    
    template <class T, class = void>
    constexpr bool is_iterator_v = false;
    
    template <class T>
    constexpr bool is_iterator_v<T, std::void_t<iter_cat_t<T>>> = true;
    
    template <typename T, typename Alloc>
    template <class InputIterator, std::enable_if_t<is_iterator_v<InputIterator>, int> = 0>
    void vector<T, Alloc>::insert(iterator position, InputIterator first, InputIterator last)
    

    【讨论】:

    • 非常感谢 :)
    【解决方案2】:

    行:

    my.insert(my.begin(), 5, 6); <-- it calls second proto.
    

    InputIterator推导出为int,这将是一个完美的匹配。相反,第一个函数必须将 int 转换为 size_typevalue_type(可能不是 int)

    您应该使用SFINAE 来限制与InputIterator 概念匹配的类型的第二个,因此只会考虑第一个。

    【讨论】:

    • 感谢您的解释:)
    • 没问题,不要犹豫,为任何有用的答案投票,特别是您接受的答案
    【解决方案3】:
    int main() {
        ft::vector<int> my;
        my.insert(my.begin(), 5u, 6); <-- it calls the first prototype.
        return (0);
    }
    

    【讨论】:

    • 没错,但是ft::vector&lt;size_type&gt; ... 呢?
    猜你喜欢
    • 1970-01-01
    • 2017-07-15
    • 1970-01-01
    • 2020-10-02
    • 1970-01-01
    • 1970-01-01
    • 2012-02-04
    • 1970-01-01
    • 2013-01-22
    相关资源
    最近更新 更多