Automatic Type Inference
נניח ואנו משתמשים במחלקות של יווצרו לנו שורות אורוכות ומסובכות:
std::vector<int>::iterator iter = std::find(ids.begin(), ids.end(), 315085121);
std::pair<std::string, std::string> firstAndLastNames = std::minmax(
names.begin(), names.end()
);
std::chrono::time_point<std::chrono::system_clock> time = std::chrono::system_clock::now();
לשם כך, נוכל להשתמש ב- ובכך ניתן ל- להבין לבד מה הטיפוס.
זה לא טיפוס שיכול להחליף טיפוסים כמו פייטון, אלא פשוט המהדר יגיד לנו מהו הטיפוס ועדיין יפעלו עליו כל החוקים.
auto iter = std::find(ids.begin(), ids.end(), 315085121);
auto firstAndLastNames = std::minmax(names.begin(), names.end());
auto time = std::chrono::system_clock::now();
אם נרצה שהטיפוס יהיה רפרנס, אזי נדרש לכתוב וכך גם ל-.
vector<string> names;
vector<int> ids;
auto& namesRef = names;
const auto& idsRef = ids;
חשוב להשתמש ב- אך ורק כשסוג המשתנה ברור לגמרי ושאין שום תהיה לגביו.
אם נניח אנו לא יודעים את סוג הטיפוס המוחזר מ- מסויים לדוגמה:
template <class Sequance>
void printMax(const Sequence& seq, int n)
{
auto maxval = seq[0];
for (int i = 0; i < n; ++i)
{
maxval = seq[i] > maxval ? seq[i] : maxval;
}
cout << maxval;
}
אם נניח אנו לא יודעים את טיפוס ההחזרה כמו פה:
template <class T, class U>
auto multiply(T x, U y)
{
auto res = x * y;
return res;
}
Move Semantics
כאשר דיברנו על בנאי העתקה ואופרטור השמה, אמרנו כי אנו לא מעוניינים לבצע אותם לרוב.
לרוב ההעתקה מיותרת ופוגעת בביצועים.
lvalue is a value that can be assigned to.
rvalue is a value that can't be assigned to.
קבועים: .
return values of functions and operators: height * width or Set<int>::union(x, y)
משתנים גלובאליים: .
משתנים לוקאליים: int i; Set<int> x;.
פרמטרים לפונקציות f(x);
בתכלס, מה שאנחנו רוצים פה זה ליצור בנאים ופונקציות אשר לא ידרשו העתקות מיותרות.
נגדיר כך:
template <class T>
class Set
{
int size;
int maxSize;
T* data;
public:
Set(const Set&); // copy c'tor
Set(Set&&); // move c'tor
Set& operator=(const Set&); // copy assignment operator
Set& operator=(Set&&); // move assignment operator
};
template<class T>
Set<T>::Set(Set&& other) : size(other.size), maxSize(other.maxSize), data(other.data)
{
// other no longer controls original memory
other.size = other.maxSize = 0;
other.data = nullptr;
}
כדי להכריח הזזה נוכל להשתמש ב-.