本文介绍了模板类方法的特化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
限时送ChatGPT账号..假设我有以下课程:
template <typename T>
class MyClass
{
public:
void SetValue(const T &value) { m_value = value; }
private:
T m_value;
};
如何为 T=float(或任何其他类型)编写函数的专用版本?
How can I write a specialized version of the function, for T=float (or any other type)?
注意:简单的重载是不够的,因为我只希望该函数可用于 T=float(即 MyClass::SetValue(float) 在这种情况下没有任何意义).
Note: A simple overload won't suffice because I only want the function to be available for T=float (i.e. MyClass::SetValue(float) doesn't make any sense in this instance).
推荐答案
template <typename T>
class MyClass {
private:
T m_value;
private:
template<typename U>
void doSetValue (const U & value) {
std::cout << "template called" << std::endl;
m_value = value;
}
void doSetValue (float value) {
std::cout << "float called" << std::endl;
}
public:
void SetValue(const T &value) { doSetValue (value); }
};
或(部分模板特化):
template <typename T>
class MyClass
{
private:
T m_value;
public:
void SetValue(const T &value);
};
template<typename T>
void MyClass<T>::SetValue (const T & value) {
std::cout << "template called" << std::endl;
m_value = value;
}
template<>
void MyClass<float>::SetValue (const float & value) {
std::cout << "float called" << std::endl;
}
或者,如果您希望函数具有不同的签名
or, if you want the functions to have different signatures
template<typename T>
class Helper {
protected:
T m_value;
~Helper () { }
public:
void SetValue(const T &value) {
std::cout << "template called" << std::endl;
m_value = value;
}
};
template<>
class Helper<float> {
protected:
float m_value;
~Helper () { }
public:
void SetValue(float value) {
std::cout << "float called" << std::endl;
}
};
template <typename T>
class MyClass : public Helper<T> {
};
这篇关于模板类方法的特化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论