如何将模板化的成员函数专门化为C ++中的模板类? [英] How to specialize a templated member-function into a templated class in C++?

查看:142
本文介绍了如何将模板化的成员函数专门化为C ++中的模板类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于这个问题:如何在C ++的模板类中为单个方法创建专门化? ...



我有这个类:

 模板< typename T> 
class MyCLass {
public:
template< typename U>
U myfunct(const U& x);
};
//通用实现
模板< typename T>
模板< typename U>
U MyCLass< T> :: myfunct(const U& x){...}

我想为 double s特别指定 myfunct



  //声明特殊化
模板<>
模板< typename T>
double MyCLass< T> :: myfunct(const double& x);

//做它
模板<>
模板< typename T>
double MyCLass< T> :: myfunct(const double& x){...}

但它不起作用。

解决方案

这在C ++中是不可能的。如果您还专门化了所有封闭的类模板,则只能专门化成员函数模板。



但是,无论如何,它通常更适合重载函数模板(详情请参阅 Herb Sutter的文章)。所以简单地做到这一点:

  template< typename T> 
class MyCLass {
public:
template< typename U>
U myfunct(const U& x);

double myfunct(double x);
};


With regards to this question: How to create specialization for a single method in a templated class in C++? ...

I have this class:

template <typename T>
class MyCLass {
public:
  template <typename U>
  U myfunct(const U& x);
};
// Generic implementation
template <typename T>
template <typename U>
U MyCLass<T>::myfunct(const U& x) {...}

And I want to specialize myfunct for doubles.

This is what I do:

// Declaring specialization
template <>
template <typename T>
double MyCLass<T>::myfunct(const double& x);

// Doing it
template <>
template <typename T>
double MyCLass<T>::myfunct(const double& x) {...}

But it does not work.

解决方案

That's not possible in C++. You can only specialise a member function template if you also specialise all enclosing class templates.

But anyway, it's generally better to overload function templates instead of specialising them (for details see this article by Herb Sutter). So simply do this:

template <typename T>
class MyCLass {
public:
  template <typename U>
  U myfunct(const U& x);

  double myfunct(double x);
};

这篇关于如何将模板化的成员函数专门化为C ++中的模板类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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