c++ - 在实例上调用时未找到模板类中的模板成员函数

标签 c++ templates c++14

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/

相关文章:

c++ - 使用键值对为零的 k 个桶初始化 c++14 unordered_map

c++ - 为什么在这种情况下 decltype 行为不同于 libstdc++ 的正常表达式?

c++ - 使用动态分配的变量和 _chdir windows 函数时堆损坏

c++ - 是否有用于 C 或 C++ 的跨平台 gzip 处理器库?

C++如何访问派生类中的基类静态成员?

c++ - 带有函数指针参数的模板类

c++ - 函数 && 限定符行为

c++ - 为 cublasSgemm 使用指向 vector<T>::data() 的指针

C++ - 模板化均匀分布?

c++ - CRTP 和基类定义的类型的可见性