问题包装std :: find。无法专门化功能模板

问题描述 投票:0回答:2

我正在尝试创建一个方便功能my::find包裹std::findstd::vector类型。它可能不是很有用,但它使代码更清洁。不幸的是我无法使返回类型工作。看例子:

#include <vector>

namespace my {
    template<typename T>
    inline typename std::vector<T>::iterator::type find(const std::vector<T>& vector, const T& value)
    {
        return std::find(vector.begin(), vector.end(), value);
    }

    template<typename T>
    inline bool contains(const std::vector<T>& vector, const T& value)
    {
        return std::find(vector.begin(), vector.end(), value) != vector.end();
    }
}

bool a() {
    std::vector<float> v;
    float a = 0.0f;
    auto found = my::find(v, a);
    return found != v.end();
}

bool b() {
    std::vector<float> v;
    float a = 0.0f;
    return my::contains(v, a);
}

我也创建了一个类似的my::contains函数,它工作正常。

当我尝试使用my::find时,我收到错误:

[x64 msvc v19.16 #1] error C2672: 'my::find': no matching overloaded function found
[x64 msvc v19.16 #1] error C2893: Failed to specialize function template 'std::vector<T,std::allocator<_Ty>>::iterator::type my::find(const std::vector<T,std::allocator<_Ty>> &,const T &)'
[x64 msvc v19.16 #1] note: With the following template arguments:
[x64 msvc v19.16 #1] note: 'T=float'

这是一个神韵:https://godbolt.org/z/ri_xoV

c++ c++11 std
2个回答
1
投票

你弄乱了返回类型的东西。这应该工作:

#include <vector>

namespace my {
    template<typename T>
    inline typename std::vector<T>::const_iterator find(const std::vector<T>& vector, const T& value)
    {
        return std::find(vector.begin(), vector.end(), value);
    }

    template<typename T>
    inline bool contains(const std::vector<T>& vector, const T& value)
    {
        return std::find(vector.begin(), vector.end(), value) != vector.end();
    }
}

bool a() {
    std::vector<float> v;
    float a = 0.0f;
    auto found = my::find(v, a);
    return found != v.end();
}

bool b() {
    std::vector<float> v;
    float a = 0.0f;
    return my::contains(v, a);
}

-1
投票

如果你使用的是C ++ 14,那就更好了。

#include <vector>

namespace my {
    template<typename T>
    inline auto find(const std::vector<T>& vector, const T& value)
    {
        return std::find(vector.begin(), vector.end(), value);
    }

    template<typename T>
    inline bool contains(const std::vector<T>& vector, const T& value)
    {
        return std::find(vector.begin(), vector.end(), value) != vector.end();
    }
}

甚至不打扰指定返回类型,并且不会出现错误。打字少了!

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