c++ - 显式特化,C++

标签 c++ explicit-specialization

如何为对象编写显式特化

Car<T>

在虚方法 clear() 中?

template <class U>
class List
{
   public:
        virtual void clear();

};


template <class T>
template <>
void List < Car <T> >::clear()   //Specialization U = Car <T>, compiler error
{
    ....
}

类车:

template <class T>
class Car
{
   T speed;
   ...
}

编译错误:

错误 16 error C3855: 'List': 模板参数 'Car' 与声明 h:...\List.hpp 不兼容 75 Error 20 error C2264: 'List::clear' : 函数定义或声明错误;函数未调用 h:...\List.hpp 75

但是这个构造是可以的

template <>
void List < Car <double> >::clear()   //Specialization U = Car <T>, compiler error
{
    ....
}

最佳答案

我认为您可以这样做的唯一方法是:

template<class T>
class Car
{
};

template <class U>
class List
{
   public:
        virtual void clear();

};

template <class T>
class List<Car<T> >
{
    public:
        virtual void clear() { /* specialization */ }
};

或者,非内联版本:

template <class T>
class List<Car<T> >
{
    public:
        virtual void clear();
};

template <class T>
void List<Car<T> >::clear() {
   /* specialization */ 
}

因为你不是真正的专业List<T>但是,考虑到模板类型仍然出现,您只是对其进行了部分特化。无论如何,我的推论可能是错误的。

关于c++ - 显式特化,C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4759251/

相关文章:

c++ - 使用显式实例化设置类模板的方法

c++ - VS 2010,C++ 项目中的代码导航

c++ - 是否可以直接从队列成员函数访问一对成员变量?

c++ - 使用 *(pointer+i) 与 pointer[i]

c++ - 模板变量的显式特化

c++ - 我可以创建匹配枚举类型的类模板的部分模板特化吗?

c++ - 声明不能解决 'explicit specialization after instantiation' 错误

c++ - 重载模板函数时显式特化和常规函数之间的区别

c++ - 赋值运算符是否调用复制构造函数?

c++ - 在模板类中定义的友元函数