[英]C++ - how to implement templated member function outside a templated class
[英]How to specialize a templated member-function into a templated class in C++?
关于这个问题: 如何在C ++的模板化类中为单个方法创建特化? ...
我有这门课:
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) {...}
而且我想专注于myfunct
for double
s。
这就是我做的:
// 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) {...}
但它不起作用。
这在C ++中是不可能的。 如果您还专门化所有封闭的类模板,则只能专门化成员函数模板。
但无论如何,通常更好的是重载函数模板而不是专门化它们(详见Herb Sutter的这篇文章 )。 所以简单地这样做:
template <typename T>
class MyCLass {
public:
template <typename U>
U myfunct(const U& x);
double myfunct(double x);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.