2

我有以下课程:

#include <set>
#include <stack>
#include <queue>
#include <string>

template <typename T>
class MySet
{
    public:
        const std::stack<T> data() const
        {
            std::stack<T> other_cont ( typename std::stack<T>::container_type ( cont.begin(), cont.end() ) );
            return other_cont;
        }

    private:
        std::set<T> cont;
};

以及以下代码:

MySet<std::string> a;
MySet<int> b;

const std::stack<std::string> s = a.data();
const std::queue<int> q = b.data();

我想使用一个模板化成员函数来初始化任何适配器类型。到目前为止,它只适用于stackor queue,我不知道如何使用模板来概括它。

这是我尝试过的:

template <template <typename> typename M>
const M<T> data() const
{
    M<T> other_cont ( typename M<T>::container_type ( cont.begin(), cont.end() ) );
    return other_cont;
}

编译器说它不能推导出模板参数M

4

2 回答 2

3

The simple approach is to use a conversion operator:

#include <set>
#include <stack>
#include <queue>
#include <string>

template <typename T>
class MySet
{
    public:
        template <typename O, typename = typename O::container_type>
        operator O() const
        {
            return O(typename O::container_type(cont.begin(), cont.end()));
        }

    private:
        std::set<T> cont;
};

Using this approach the notation is different, though: there is no data() member being used:

int main()
{
    MySet<std::string> s;
    std::stack<std::string> st = s;
    std::queue<std::string> qu = s;
} 

If you want to use a data() member and get different types out of the result, you'll need to return a proxy which converts appropriately upon access:

#include <set>
#include <stack>
#include <queue>
#include <string>

template <typename T>
class MySet
{
    public:
        class Proxy {
            std::set<T> const* set;
        public:
            Proxy(std::set<T> const* s): set(s) {}
            template <typename O, typename = typename O::container_type>
            operator O() const
            {
                return O(typename O::container_type(set->begin(), set->end()));
            }
        };

        Proxy data() const { return Proxy{&this->cont}; }
    private:
        std::set<T> cont;
};

int main()
{
    MySet<std::string> s;
    std::stack<std::string> st = s.data();
    std::queue<std::string> qu = s.data();
} 
于 2016-12-19T18:17:46.323 回答
3

考虑您的调用代码:

a.data()

这里没有什么data()可以推断它的返回类型。你必须明确地精确它,比如:

a.data<std::stack>()

但是,根据您的评论,您无法编辑使用代码。您可以做的是使用模板类型转换运算符:

template <typename M>
operator M() const
{
    M other_cont ( typename M::container_type ( cont.begin(), cont.end() ) );
    return other_cont;
}

为了保持代码不被编辑,你的data方法应该返回这个对象:

const MySet<T> data() const
{
    return *this;
}
于 2016-12-19T18:19:09.453 回答