मेरे पास यह सुंदर सरल कार्य है, मेरे पास कुछ मूल्य हैं जिन्हें गणना करने की आवश्यकता है, लेकिन केवल एक बार और सबसे अच्छा समय संकलन समय पर होगा। ये मान केवल इस फ़ंक्शन के भीतर मायने रखते हैं। क्या यह constexpr का एक अच्छा उपयोग है या क्या मुझे बस स्थिर स्थिर घोषित करना चाहिए?क्या मुझे इस तरह का कंस्ट्रैक्स का उपयोग करना चाहिए?
ps मुझे पता है कि प्रदर्शन अंतर कोई फर्क नहीं पड़ता है, लेकिन मैं इसे "दाएं" सी ++ 11 तरीके से करना चाहता हूं।
void MainWindow::UpdateDateTimes()
{
// for some dumb reason DateTime only has add seconds method
// so we have to calculate the seconds per hour and the number of hours
// we do this with static constant values so that the calculations
// only happen once.
static constexpr const int secsPerHour = 60 * 60;
static constexpr const int cdtOffsetHours = -5;
static constexpr const int edtOffsetHours = -4;
static constexpr const int cetOffsetHours = 2;
static constexpr const int cdtOffsetSecs = secsPerHour * cdtOffsetHours;
static constexpr const int edtOffsetSecs = secsPerHour * edtOffsetHours;
static constexpr const int cetOffsetSecs = secsPerHour * cetOffsetHours;
QDateTime time(QDateTime::currentDateTimeUtc());
ui->mTimeLocal->setDateTime(time.toLocalTime());
ui->mTimeCDT->setDateTime(time.addSecs(cdtOffsetSecs));
ui->mTimeEDT->setDateTime(time.addSecs(edtOffsetSecs));
ui->mTimeCET->setDateTime(time.addSecs(cetOffsetSecs));
}
'constexpr' का अर्थ है 'const'। – Xeo
'const int 'प्रत्येक के लिए पर्याप्त है, लेकिन' constexpr int' अधिक स्पष्ट हो सकता है। कृपया दो मिश्रण न करें। – ipc
प्रत्येक बार फ़ंक्शन कहलाता है, और इसलिए गणना भी बनाई जानी चाहिए? मुझे पता है कि इसे अनुकूलित किया जा सकता है, लेकिन मैं इसे सही करना चाहता हूं ताकि कोड कहता है कि मैं वास्तव में क्या कह रहा हूं। – EddieV223