Suppose I have the following class:
template <typename T>
class MyClass
{
public:
void SetValue(const T &value) { m_value = value; }
private:
T m_value;
};
How can I write a specialized version of the function, for T=float (or any other type)?
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).
The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation is called a specialization.
Template in C++is a feature. We write code once and use it for any data type including user defined data types. For example, sort() can be written and used to sort any data type items. A class stack can be created that can be used as a stack of any data type.
What are the two specializations of I/O template classes in C++? Explanation: The I/O specialization is made with wide character and 8-bit characters.
An explicit specialization of a function template is inline only if it is declared with the inline specifier (or defined as deleted), it doesn't matter if the primary template is inline.
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); }
};
or (partial template specialization):
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> {
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With