निम्न प्रोग्राम का निरीक्षण करें जिसमें एक फ़ंक्शन अपेक्षित प्रकार और किसी भी प्रकार को स्वीकार करता है जो उस प्रकार का टाइपपीफ है।मैं दृढ़ता से टाइप किए गए गैर-आदिम प्रकार कैसे टाइप करूं?
//a user defined type
class Widget{};
//a function that takes a Widget
void function (Widget w){}
int main(){
//make a typedef (this is C++11 syntax for a typedef. It's the same thing)
using Gadget = Widget;
//make the two "different types" (well.. they're not really different as you will see)
Widget w;
Gadget g;
//call a function that should ONLY accept Widgets
function(w); //works (good)
function(g); //<- works (I do not want this to compile though)
}
जैसा कि आप देख सकते हैं, एक टाइपिफ़ वास्तव में एक नए प्रकार को अलग नहीं करता है। मैंने सोचा कि इस प्रकार से प्राप्त करने के लिए:
//inherit instead
class Gadget: public Widget{};
//make the two "different types"
Widget w;
Gadget g;
//call the function that should ONLY accept widgets
function(w); //works (good)
function(g); //<- works (I do not want this to compile though)
वही समस्या।
#include <boost/serialization/strong_typedef.hpp>
//a user defined type
class Widget{};
//a function that takes the user defined type
void function (Widget w){}
int main(){
//try to strongly typedef
BOOST_STRONG_TYPEDEF(Widget, Gadget)
//make the two "different types"
Widget w;
Gadget g;
//call the function that should ONLY accept widgets
function(w);
function(g);
}
त्रुटियों संकलन:
In member function ‘bool main()::Gadget::operator==(const main()::Gadget&) const’:
error: no match for ‘operator==’ (operand types are ‘const Widget’ and ‘const Widget’)
BOOST_STRONG_TYPEDEF(Widget, Gadget)
^
In member function ‘bool main()::Gadget::operator<(const main()::Gadget&) const’:
error: no match for ‘operator<’ (operand types are ‘const Widget’ and ‘const Widget’)
BOOST_STRONG_TYPEDEF(Widget, Gadget)
^
जाहिर BOOST_STRONG_TYPEDEF केवल आदिम प्रकार पर काम करता है
बढ़ावा को देखते हुए, मैं एक मजबूत typedef की कोशिश करने के बारे में सोचा।
//I want the functionality, but these are NOT the same type!
class Gadget: public Widget{
operator Widget() = delete;
};
कि या तो काम नहीं किया:
मैं विरासत फिर से करते हैं, लेकिन अंतर्निहित रूपांतरण रोकने की कोशिश की।
सवाल:
- strong_typedef केवल आदिम प्रकार पर काम क्यों बढ़ावा देता है?
- मजबूत_typef को बढ़ावा देने के समान कार्यक्षमता प्राप्त करने के लिए मैं एक गैर-आदिम प्रकार को 'टाइपिफ़' कैसे कर सकता हूं?
मुझे लगता है कि मैं 'विजेट विजेटबेस' श्रेणी दूंगा, और 'कक्षा विजेट: सार्वजनिक विजेटबेस' करूँगा; 'कक्षा गैजेट: सार्वजनिक विजेटबेस'। – xis
@zneak: यही है 'BOOST_STRONG_TYPEDEF' करता है। – Deduplicator
@Deduplicator कार्यान्वयन को देखते हुए strong_typedef सदस्य का उपयोग करता है और विरासत नहीं। – pmr