将非模板类型传递给模板函数?

0 c++ templates set

template <class T, class Compare = std::less<T>>
class Test
{
    protected:
        std::set<T, Compare> s;
    public:
        Test(std::set<T, Compare>&);
        void add(const std::set<T, Compare>&);
}

template <class T, class Compare>
Test<T, Compare>::Test(std::set<T, Compare>& t)
{
    s = t;
}

template <class T, class Compare>
void Test<T, Compare>::add(const std::set<T, Compare>& t)
{
    typename std::set<T, Compare>::iterator itr;
    for (itr = t.begin(); itr != t.end(); itr++)
    {
        s.insert(*itr);
    }
}
Run Code Online (Sandbox Code Playgroud)

我有以下设置:

std::set<int, std::less<int>> s;
std::set<int, std::greater<int>> si;
s.insert(3);
si.insert(5);

Test<int> a(s);
a.add(si)
Run Code Online (Sandbox Code Playgroud)

现在我明白为什么编译器抛出:没有匹配的函数来调用 'Test::add(std::set<int, std::greater >&)' a.set_union(si)

但我能让它以某种方式工作吗?

use*_*570 5

问题是是 类型 因此 的参数是 a而您传递的参数是 类型。sstd::set<int, std::less<int>>addconst std::set<int, std::less<int>>&sistd::set<int, std::greater<int>>

解决这个问题的一种方法是制作add一个成员函数模板,如下所示:

template <class T, class Compare = std::less<T>>
class Test
{
    protected:
        std::set<T, Compare> s;
    public:
        Test(std::set<T, Compare>&);
        //declaration of member function template add
        template<typename SecCompare>
        void add(const std::set<T, SecCompare>&);
};

template <class T, class Compare>
Test<T, Compare>::Test(std::set<T, Compare>& t)
{
    s = t;
}

//implementation of member function template add
template <class T, class Compare>
template<typename SecCompare>
void Test<T, Compare>::add(const std::set<T, SecCompare>& t)
{
    typename std::set<T, Compare>::iterator itr;
    for (itr = t.begin(); itr != t.end(); itr++)
    {
        s.insert(*itr);
    }
}
Run Code Online (Sandbox Code Playgroud)

工作演示