c++ - 如何调用带参数的类模板函数

标签 c++

在尝试将模板参数传递给函数调用时,我不断得到预期的主表达式..

我的错误看起来像:

In PtrAllocator<T, Pool>::allocate(PtrAllocator<T, Pool>::size_type, const void*)': expected primary-expression before '>' token

In PtrAllocator<T, Pool>::max_size() const': expected primary-expression before '>' token

我的代码如下:

template<typename T, typename Pool>
class PtrAllocator : public BasicAllocator<T>
{
    private:
        Pool pool;

    public:
        typedef typename BasicAllocator<T>::pointer pointer;
        typedef typename BasicAllocator<T>::size_type size_type;
        typedef typename BasicAllocator<T>::value_type value_type;

        template<typename U>
        struct rebind {typedef PtrAllocator<U, Pool> other;};

        PtrAllocator(Pool&& pool) : pool(pool) {}

        pointer allocate(size_type n, const void* hint = 0) {return static_cast<pointer>(pool.allocate<T>(n, hint));}
        void deallocate(void* ptr, size_type n) {pool.deallocate(static_cast<pointer>(ptr), n);}
        size_type max_size() const {return pool.max_size<T>();}
};

class Pool
{
    public:
        template<typename T>
        void* allocate(std::size_t n, const void* hint = 0) {return ::operator new(n * sizeof(T));}

        template<typename T>
        void deallocate(T* ptr, std::size_t n) {::operator delete(ptr);}

        template<typename T>
        std::size_t max_size() const {return std::numeric_limits<std::size_t>::max() / sizeof(T);}
};

int main()
{
    PtrAllocator<int, Pool> alloc = PtrAllocator<int, Pool>(Pool());
    std::vector<int, PtrAllocator<int, Pool>> v(alloc);
    v.resize(1000); //this line is causing the error.
}

错误发生在 PtrAllocator::allocate 调用 Pool::allocate 时。同样的事情发生在 max_size 上,但不会发生在 deallocate 上。 知道为什么它不允许我指定模板参数吗?

最佳答案

你需要告诉编译器 allocate是模板,否则表达式会产生歧义:

pool.template allocate<T>(n, hint)

解释见Where and why do I have to put the “template” and “typename” keywords? .

基本问题是没有template告诉编译器 allocate是一个模板,表达式可以用不同的方式解释。也就是说,表达式是有歧义的。要了解如何操作,请查看以下示例:

struct my_pool {
    int allocate = 0; // allocate is a data member, not a template!
};

template <typename Pool>
void foo() {
    Pool pool;
    int T = 0, n = 0, hint = 0;
    pool.allocate<T>(n, hint); // *
}

int main() {
    foo<my_pool>();
}

我用星号标记的那一行与您的表达方式完全相同,但它的意思完全不同。它实际上相当于 (pool.allocate < T) > (n, hint) .即 <>不再是模板参数定界符——它们是关系运算符!我正在比较数据成员 pool.allocateT .

关于c++ - 如何调用带参数的类模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20868600/

相关文章:

c++ - 如何知道设备何时从网络中删除使用 Bonjour C 库

c++ - 使用 boost Spirit x3 解析为集合

c++ - 我们可以在构造函数中使用 'this' 指针吗

c++ - 理解c++中动态内存分配的使用

c++ - 如何使用已删除的复制构造器模拟方法返回对象?

c++ - read int per line c++ 错误需要解决方案

c++ - 对称矩阵中的线性索引

c++ - 为什么这个单例实现使用私有(private)类(C++)?

c++ - 判断鼠标是否水平移动(C++)

c++ - 不允许从 'const char *' 到 'void *' 的 static_cast