नीचे दिए गए कोड के संबंध में, कंपाइलर किस टेम्पलेट फ़ंक्शन को कॉल करने का विकल्प चुनता है? यदि कॉन्स टी & फ़ंक्शन छोड़ा गया है, तो टी & फ़ंक्शन हमेशा कॉल किया जाता है। यदि टी & फ़ंक्शन छोड़ा गया है, तो कॉन्स टी & फ़ंक्शन हमेशा कॉल किया जाता है। यदि दोनों शामिल हैं, तो परिणाम नीचे दिए गए हैं।संकलन कैसे कॉल करता है कि कौन सा टेम्पलेट फ़ंक्शन कॉल करना है?
#include <iostream>
#include <typeinfo>
template <typename T>
void function(const T &t)
{
std::cout << "function<" << typeid(T).name() << ">(const T&) called with t = " << t << std::endl;
}
template <typename T>
void function(T &t)
{
std::cout << "function<" << typeid(T).name() << ">(T&) called with t = " << t << std::endl;
}
int main()
{
int i1 = 57;
const int i2 = -6;
int *pi1 = &i1;
int *const pi3 = &i1;
const int *pi2 = &i2;
const int *const pi4 = &i2;
function(pi1); ///just a normal pointer -> T&
function(pi2); ///cannot change what we point to -> T&
function(pi3); ///cannot change where we point -> const T&
function(pi4); ///cannot change everything -> const T&
return 0;
}
/* g++ output:
function<Pi>(T&) called with t = 0x22cd24
function<PKi>(T&) called with t = 0x22cd20
function<Pi>(const T&) called with t = 0x22cd24
function<PKi>(const T&) called with t = 0x22cd20
*/
/* bcc32 output:
function<int *>(T&) called with t = 0012FF50
function<const int *>(T&) called with t = 0012FF4C
function<int *>(const T&) called with t = 0012FF50
function<const int *>(const T&) called with t = 0012FF4C
*/
/* cl output:
function<int *>(T&) called with t = 0012FF34
function<int const *>(T&) called with t = 0012FF28
function<int *>(const T&) called with t = 0012FF34
function<int const *>(const T&) called with t = 0012FF28
*/
एक छोटी सी चाल है, जब आप जी का उपयोग कर ++ होने के लिए होने की स्पष्ट रूप से निरंतर सूचक। '__PRETTY_FUNCTION__' आपके फ़ंक्शन का वर्णन करने वाली एक अच्छी तरह से स्वरूपित स्ट्रिंग प्रदान करता है, जिसमें" पीआई "के बजाय टेम्पलेट पैरामीटर प्रकार [" int * "शामिल हैं)। जब यह टेम्पलेट्स काम करता है, तो सीखने के दौरान मुझे यह अमूल्य लगता है, क्योंकि 'टाइपिड (टी) .name()' के लिए डिफ़ॉल्ट व्यवहार g ++ के तहत डिफ़ॉल्ट क्रिप्टिक है। मेरा मानना है कि '__FUNCSIG__' वीएस के तहत समान कार्यक्षमता प्रदान करता है, लेकिन मुझे इसकी पुष्टि करने के लिए इसका उपयोग नहीं है। –