C++ - 通过模板类进行模板特化

标签 c++ templates template-specialization

我有一个模板类,我需要在其中专门为同样模板化的类提供一些方法。更具体地说:我尝试将智能数组和共享指针结合起来:

template <class T>
int sortedArray< smartPtr<T> >::insert(const T& object) {
...
}

使用此语法我收到以下错误:

main.cpp:162:55: error: invalid use of incomplete type ‘class sortedArray<smartPtr<T> >’
int sortedArray< smartPtr<T> >::insert(const T& object) {
                                                      ^
main.cpp:87:7: error: declaration of ‘class sortedArray<smartPtr<T> >’
 class sortedArray {
       ^

有可能做这种事情吗?

最佳答案

您可以部分特化整个类模板:

template <typename T>
struct sortedArray<smartPtr<T>> {
    void insert(const smartPtr<T>& object) {
        ....
    }

    // everything else
};

或者您可以显式专门化一个方法:

An explicit specialization may be declared for a function template, a class template, a member of a class template or a member template.

如:

template <>
void sortedArray<smartPtr<int>>::insert(const smartPtr<int>& object) {
    ...
}

但是你不能部分只专门化一个方法。

关于C++ - 通过模板类进行模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29657962/

相关文章:

c++ - 将 GCC 的 typeof() 扩展与成员访问相结合

c++ - 跨多个 C++ 项目的编译时配置

c++ - 为什么这个程序告诉我传递了无效的参数?

C++ 可变模板参数和元组迭代

c++ - 混合模板、多重继承和非默认构造函数

c++ - 特化非模板类的成员函数模板

c++ - 在不使用继承或类特化的情况下禁用成员函数和变量

c++ - Tic Tac Toe 预期主要表达之前

c++ - 关于优化不会出现在 EXE 中的 DLL 有什么注意事项吗?

c++ - 在C++中,将左值完美转发到函数模板的正确方法是什么?