【问题标题】:When I need to specialize the typename I declared in my template class, what arguments I must use?当我需要专门化我在模板类中声明的类型名时,我必须使用哪些参数?
【发布时间】:2009-01-26 15:42:08
【问题描述】:

我有一个线程安全向量的模板类:

template <class T>
class SharedVector {
    std::vector<T> vect;
    CRITICAL_SECTION cs;
    SharedVector(const SharedVector<T>& rhs) {}
public:
    typedef typename std::vector<T>::size_type SizeType;
    SharedVector();
    void PushBack(const T& value);
    void PopBack();
    SizeType size();
    const T& operator[](int index);
    void erase(int index);
    void Lock(); 
    void Unlock(); 
    virtual ~SharedVector();
};

然后我想在 TCP 服务器的客户端管理器中使用它来委派一些 从客户经理到这个向量的职责:

class TCPClientManager {
    TCPClientManager(const TCPClientManager&) {}
    TCPClientManager& operator=(const TCPClientManager&) {}
    SharedVector<Connection*> connections;
public:
    TCPClientManager();
    SharedVector<>::SizeType size(); //here is the problem
    void addConnection(const Client&); 
    void breakConnection(int); 
    void deleteConnection(int); 
    void Lock();
    void Unlock();
    ~TCPClientManager();
};

typename SharedVector<>::SizeType TCPClientManager::size() {
    return connections.size();
}

我需要声明检索值的类型。编译器说模板的参数太少。

【问题讨论】:

    标签: c++ templates


    【解决方案1】:

    您必须为 SharedVector 模板提供类型参数:

    SharedVector<Connection*>::SizeType size(); 
    ....
    SharedVector<Connection*>::SizeType TCPClientManager::size() {
        return connections.size();
    }
    

    因为Connection*类型不是TCPClientManager中的模板参数,而是显式选择的类型,所以不需要在SharedVector&lt;Connection*&gt;::SizeType之前加上typename

    【讨论】:

      【解决方案2】:

      (除了litb,真的)

      你应该 typedef 你的容器;即typedef SharedVector&lt;Connection*&gt; ConnectionPool;。这将允许您写ConnectionPool::size_type

      注意:container::size() 应该返回 container::size_type,而不是 container::SizeType。这使得容器与 STL 兼容。同理,迭代器类应该是container::iterator,添加元素由container::push_back(container::value_type const&amp;)等完成。

      【讨论】:

        猜你喜欢
        • 2020-07-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-08
        • 1970-01-01
        • 2012-07-25
        • 1970-01-01
        相关资源
        最近更新 更多