简体   繁体   English

如何专门化模板

[英]how to specialize the template

consider existing situation 考虑现有情况

template<typename T, int N = 10>
struct A
{
    //whatever
};

template <typename T1,typename T2, typename T3>
struct B;

template<typename T2, typename T3>
struct B<double,T2,T3>
{
    //...

protected:
   A<T2> myA;
};

Now I'm interesting to be able to pass different than the default N to A in specialization of B without changing the declaration of B . 现在我感兴趣的是能够通过不同于默认NA在专业化B不改变的声明B Is it possible? 可能吗?

I can think about 我可以考虑一下

template<typename T2, typename T3, int N>
struct B<double,T2,T3>
{
    //...

protected:
    A<T2,N> myA;
};

but then I'm not sure how to use it... 但后来我不确定如何使用它......

Well, your class B is only usable like that: 好吧,你的B级只能这样使用:

B<double, C, D> b;

Where C and D are types themselves. CD本身就是类型。

You cannot pass a number there. 你不能在那里传递数字。 Specialization won't help you. 专业化不会帮助你。 Specialization don't change how you can use the class or what parameters you can pass, but you can only change what the implementation for a certain set of parameter. 专业化不会改变您可以使用类的方式或可以传递的参数,但您只能更改某个参数集的实现。 With that said, 照这样说,

What I suggest is to change the declaration of B to be like: 我建议将B的声明改为:

template <typename, typename, typename, int = 10>
struct B;

Ans the specialization to be like that: Ans的专业化是这样的:

template<typename T2, typename T3, int N>
struct B<double,T2,T3, N> {
    //...

protected:
    A<T2, N> myA;
};

So your class is both useable like before, and like this: 所以你的课程既像以前一样可用,就像这样:

B<double, C, D, 11> b;

If you really cannot change what the parameter are, you can further specialize it to recieve a type that has a number as template parameter: 如果你真的无法改变参数是什么,你可以进一步专门化它来接收一个带有数字作为模板参数的类型:

template<typename, int>
struct TypeAndNumber {};

And change your socialization to that: 并将你的社交化改变为:

template<typename T2, typename T3, int N>
struct B<TypeAndNumber<double, N>, T2, T3> {
    //...

protected:
    A<T2, N> myA;
};

Now your class can be useable like that: 现在你的课可以这样使用:

B<TypeAndNumber<double, 33>, C, B> b;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM