模板类特化,其中模板参数是模板

时间:2023-03-10
本文介绍了模板类特化,其中模板参数是模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我想知道是否有可能发生类似的事情.基本上,我有一个模板化类,它偶尔会使用模板化类的对象.我想将它(或只是一个成员函数)专门用于特定的模板化类,但是该类的通用"形式.

I wondering if something similar to this is possible. Basically, I have a templated class that occasionally takes objects of templated classes. I would like to specialize it (or just a member function)for a specific templated class, but the 'generic' form of that class.

template<typename T, typename S>
class SomeRandomClass
{
    //put something here
};

template<typename T>
class MyTemplateClass
{
    void DoSomething(T & t) {
       //...something
    }
};

template<>
void MyTemplateClass< SomeRandomClass<???> >::DoSomething(SomeRandomClass<???> & t)
{
    //something specialized happens here
}

用适当的类型(double 等)替换问号是可行的,但我希望它保持通用.我不知道该放什么,因为没有定义任何类型.我环顾四周,了解了模板模板参数,并尝试了各种组合都无济于事.感谢您的帮助!

Replacing the question marks with appropriate types (double, etc) works, but I would like it to remain generic. I don't know what to put there, as any types wouldn't have been defined. I've looked around, and learned about template template parameters, and tried various combinations to no avail. Thanks for the help!

推荐答案

可以像这样专门化类

template <>
template <typename T,typename S>
class MyTemplateClass <SomeRandomClass<T,S> >
{
    void DoSomething(SomeRandomClass<T,S>& t) { /* something */ }
};

只对成员方法进行特化是不可能的,因为特化是针对整个类的,您必须定义一个新类.但是,您可以这样做

It's not possible to specialize just the member method, because the specialization is on the class as a whole, and you have to define a new class. You can, however, do

template <>
template <typename T,typename S>
class MyTemplateClass <SomeRandomClass<T,S> >
{
    void DoSomething(SomeRandomClass<T,S>& t);
};

template <>
template <typename T,typename S>
void MyTemplateClass<SomeRandomClass<T,S> >::DoSomething(SomeRandomClass<T,S>& t)
{
    // something
}

拆分声明和定义.

这篇关于模板类特化,其中模板参数是模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:C++ 模板中的名称查找 下一篇:C++ 模板会使程序变慢吗?

相关文章