Code:
template<class T>
struct A {
void f1() {};
void f2() {};
};
template<>
struct A<int> {
void f2() {};
};
int main() {
A<int> data;
data.f1();
data.f2();
};
test.cpp: In function 'int main()':
test.cpp:16: error: 'struct A<int>' has no member named 'f1'
Basically, I only want to specialize one function and use the common definition for other functions. (In actual code, I have many functions which I don't want to specialize).
How to do this? Thanks!
An individual class defines how a group of objects can be constructed, while a class template defines how a group of classes can be generated. Note the distinction between the terms class template and template class: Class template.
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.
Member functions of class templates (C++ only) You may define a template member function outside of its class template definition. The overloaded addition operator has been defined outside of class X . The statement a + 'z' is equivalent to a. operator+('z') .
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.
Would this help:
template<typename T>
struct A
{
void f1()
{
// generic implementation of f1
}
void f2()
{
// generic implementation of f2
}
};
template<>
void A<int>::f2()
{
// specific implementation of f2
}
Consider moving common parts to a base class:
template <typename T>
struct ABase
{
void f1();
};
template <typename T>
struct A : ABase<T>
{
void f2();
}
template <>
struct A<int> : ABase<int>
{
void f2();
};
You can even override f1
in the derived class. If you want to do something more fancy (including being able to call f2
from f1
code in the base class), look at the CRTP.
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