namespace {
enum class API { CPU, CUDA };
template <API Api>
class Allocator {
void* malloc(int size) const;
void free(void* ptr) const;
template <typename T>
T* alloc1(int num) const {
return static_cast<T*>(malloc(num * static_cast<int>(sizeof(T))));
}
};
template <typename T, API Api>
T* alloc2(const Allocator<Api> allocator, int num) {
return static_cast<T*>(allocator.malloc(num * static_cast<int>(sizeof(T))));
}
template <>
class Allocator<API::CPU> {
public:
void* malloc(int size) const { return nullptr; }
void free(void* ptr) const {}
};
Allocator<API::CPU> allocator;
int* ptr1 = allocator.template alloc1<int>(1);
int* ptr2 = alloc2<int>(allocator, 1);
}
alloc1
调用没有编译错误.../src/test.cc:29:32: error: no member named 'alloc1' in '(anonymous namespace)::Allocator<API::CPU>'
int* ptr1 = allocator.template alloc1<int>(1);
^
.../src/test.cc:29:38: error: expected unqualified-id
int* ptr1 = allocator.template alloc1<int>(1);
^
.../src/test.cc:29:42: error: expected '(' for function-style cast or type construction
int* ptr1 = allocator.template alloc1<int>(1);
~~~^
删除
template
没有帮助:.../src/test.cc:29:33: error: expected '(' for function-style cast or type construction
int* ptr1 = allocator.alloc1<int>(1);
~~~^
.../src/test.cc:29:23: error: no member named 'alloc1' in '(anonymous namespace)::Allocator<API::CPU>'; did you mean 'malloc'?
int* ptr1 = allocator.alloc1<int>(1);
^~~~~~
malloc
我正在使用带有 C++14 标准的 Clang 9。
alloc2
作为一种解决方法,所以我只想知道为什么alloc1
没有或声明/调用它的正确方法是什么。编辑:事实证明,提供
Allocator<API::CPU>::malloc
的特化/free
而不是 Allocator<API::CPU>
的特化给出了我预期的行为,但在我原来的情况下,继承可能更合适。
最佳答案
class Allocator<API::CPU>
特化根本没有定义成员函数;它仅在通用模板中定义。如果您想避免对多个规范重复相同的定义,您可以使用继承。像这样的例子:
struct BaseAllocator {
template <typename T>
T* alloc1(int num) const {
...
}
};
template <API Api>
class Allocator : public BaseAllocator {
...
};
template <>
class Allocator<API::CPU> : public BaseAllocator {
...
};
附言您的
alloc1
是私有(private)的,因此无论如何您都无法从类外访问它。
关于c++ - 在实例上调用时未找到模板类中的模板成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60847063/