有人问我问题
哪些类函数可以在 C++ 中模板化? (构造函数、析构函数、const、静态)
我是否正确理解所有成员函数(析构函数除外)都可以模板化?
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);
}
是的,它可以是模板。
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});
}
是的。
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});
}
从技术上讲,任何成员函数都可以是模板化,因为该术语包括类模板的成员函数(或类模板的成员类,或函数模板中的本地类,等),它们当然可以使用模板参数对于任何包含的模板。真正的问题是哪些成员可以是函数模板(因此根本不是函数)。
答案很简单:任何不是(预期)析构函数且不是
virtual
的成员函数都可以作为函数模板。 (构造函数模板和转换函数模板不能使用显式模板参数调用,因此必须推导它们。)
但请注意,函数模板和函数模板的特化都不能算作某些 special 成员函数,即使它可以代替它们使用(感谢抑制隐式声明或成为更好的匹配):
struct A {
template<class=int>
A(int=0); // #1, not a default constructor
template<class T>
A(T&); // #2, not a copy constructor
template<class T>
A& operator=(T&); // #3, not a copy-assignment operator
} a, // calls #1
b(a), // calls #2
&r=(a=b); // calls #3
A
这里仍然有默认的复制/移动操作,因为这些操作都不会干扰。
所有类方法除了析构函数和复制构造函数(和移动构造函数?)都可以定义为类成员模板。
其他注意事项:
参见:https://en.cppreference.com/w/cpp/language/member_template