在尝试将模板参数传递给函数调用时,我不断得到预期的主表达式..
我的错误看起来像:
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.allocate
与 T
.
关于c++ - 如何调用带参数的类模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20868600/