在实例上调用时找不到模板类中的模板成员函数 [英] Template member function in a template class not found when called on an instance
问题描述
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);
~~~^
删除模板
没有帮助:
.../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.
I am using Clang 9 with C++14 standard.
alloc2
是一种解决方法,所以我只想知道为什么 alloc1
没有,或者什么是声明/调用它的正确方法.
alloc2
works as a workaround, so I just want to know why alloc1
doesn't or what is the proper way to declare/call it.
事实证明,提供了 Allocator< API :: CPU> :: malloc
/ free
的专业化,而不是 Allocator< API的专业化::CPU>
给出了我期望的行为,但在我的原始情况下,继承可能更合适.
it turns out that providing specializations of Allocator<API::CPU>::malloc
/free
instead of a specialization of Allocator<API::CPU>
gives the behavior I expected, but probably inheritance will be more appropriate in my original situation.
推荐答案
class Allocator< API :: CPU>
专业化只是没有定义成员函数;它仅在通用模板中定义.如果要避免对多个指定重复相同的定义,则可以使用继承.例如:
class Allocator<API::CPU>
specialisation simply does not define the member function; It is only defined in the generic template. If you want to avoid repeating same definition for multiple specilisations, you can use inheritance. Like this for example:
struct BaseAllocator {
template <typename T>
T* alloc1(int num) const {
...
}
};
template <API Api>
class Allocator : public BaseAllocator {
...
};
template <>
class Allocator<API::CPU> : public BaseAllocator {
...
};
P.S.您的 alloc1
是私有的,因此无论如何您都无法从类外部访问它.
P.S. Your alloc1
is private, so you wouldn't have access to it from outside the class anyway.
这篇关于在实例上调用时找不到模板类中的模板成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!