使用模板专门化模板 [英] Specialize a template with a template

查看:229
本文介绍了使用模板专门化模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个(免费)函数模板,看起来像这样

I have a (free) function template that looks like this

template <typename T>
T get();

我现在想为一个类专门化这个函数,它本身就是一个模板。但我的编译器不想编译它,我现在问现在如果这是可能的,如何我可以实现它。只是为了这个想法,代码可以看起来像这样:(不编译)

I now want to specialize this function for a class, which itself is a template. But my compiler doesn't want to compile it, and I'm asking now if that is even possible and how I could achieve it. Just for the idea, the code could look as follows: (Doesn't compile)

template <>
template <typename T>
foo_type<T> get<foo_type<T>>()


推荐答案

你所做的是称为功能模板的 partial 专业化。但不允许功能模板的部分专门化。允许重载函数模板,但在这种情况下,也不可能,因为函数只有返回类型,并且不允许在返回类型上重载。

What you're doing is called partial specialization of function template. But partial specialization of function template is not allowed. Overloading of function template is allowed, but in this case, it is not possible either, as the function has only return type, and overloading on return type is not allowed.

所以解决方案是:

namespace details
{
     template <typename T>
     struct worker
     {
         static T get();
     };

     template <typename T> //partial specialization of class is allowed
     struct worker<foo<T>>
     {
         static foo<T> get();
     };

}

template <typename T>
T get()
{
  return details::worker<T>::get();
}






如果您定义它们以接受一个参数以使过载有效:


You could also use overloads if you define them to take one argument so as to make overload valid:

namespace details
{
     template <typename T>
     static T get(T*); 

     template <typename T> 
     static foo<T> get(foo<T>*); //now the overload is valid

}

template <typename T>
T get()
{
  return details::get<T>(static_cast<T*>(0));
}

注意参数 static_cast< T *> (0)用于帮助编译器选择正确的重载。如果 T 不是 foo< U> ,则将选择第一个重载作为参数的类型它将是 T * ,而不是 foo< U> * 。如果 T foo< U> ,则第二重载将由编译器选择,更多专门化,并且可以接受在此情况下传递给它的参数为 foo< U> *

Note that the argument static_cast<T*>(0) is used to help the compiler to select the correct overload. If T is other than foo<U>, then the first overload will be selected as the type of the argument passed to it will be T* as opposed to foo<U>*. If T is foo<U>, then the second overload will be selected by the compiler because it is more specialized, and can accept the argument passed to it which is foo<U>* in this case.

这篇关于使用模板专门化模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆