I was asked a question
Which class functions can be templated in C++? (constructor, destructor, const, static)
Did I understand correctly that all member functions (except destructor) can be templated?
Constructor / destructor
class A {
public:
template<class T>
A(T t) {
cout << t << endl;
}
/*
template<class U>
~A() { // error: destructor cannot be declared as a template
cout << "Destructor\n";
}*/
};
int main() {
A a(5);
}
Static function
Yes, it can be template.
class A {
public:
template< typename T>
static double foo( vector<T> arr );
};
template< typename T>
double A::foo( vector<T> arr ){ cout << arr[0] << endl; }
int main() {
A a;
A::foo<int>({1, 2, 3});
}
Non-constant / constant member function
Yes.
class A {
public:
template< typename T>
double foo( vector<T> arr ) const {
cout << arr[0] << endl;
}
};
int main() {
A a;
a.foo<int>({1, 2, 3});
}
template<typename T> operator double() const { return (double)T(); }
)requires
clauses.