I only have an hpp file for a school assignment in C++ (I am not allowed to add a cpp file, declaration and implementation should be both written in the file).
I wrote this code inside it:
template<class T>
class Matrix
{
void foo()
{
//do something for a T variable.
}
};
I would like to add another foo
method, but this foo()
will be specialized for only an <int>
.
I have read in some places that I need to declare a new specialization class for this to work. But what I want is that the specialized foo
will lie just beneath the original foo
, so it will look like this:
template<class T>
class Matrix
{
void foo(T x)
{
//do something for a T variable.
}
template<> void foo<int>(int x)
{
//do something for an int variable.
}
};
Thanks
There are three kinds of templates: function templates, class templates and, since C++14, variable templates. Since C++11, templates may be either variadic or non-variadic; in earlier versions of C++ they are always non-variadic.
Templates Specialization is defined as a mechanism that allows any programmer to use types as parameters for a class or a function. A function/class defined using the template is called a generic function/class, and the ability to use and create generic functions/classes is one of the critical features of C++.
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.
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.
foo
isn't a template. It's a member function of a template. Thus foo<int>
is meaningless. (Also, explicit specializations must be declared at namespace scope.)
You can explicitly specialize a member function of a particular implicit instantiation of a class template:
template<class T>
class Matrix
{
void foo(T x)
{
//do something for a T variable.
}
};
// must mark this inline to avoid ODR violations
// when it's defined in a header
template<> inline void Matrix<int>::foo(int x)
{
//do something for an int variable.
}
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