Bir işlevin hem beklenen tür hem de bu tür yazım denetimi olan herhangi bir türü kabul ettiği aşağıdaki programa dikkat edin.İlkel olmayan türleri nasıl yazarım?
//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)
}
Gördüğünüz gibi, bir yazım hatası aslında yeni bir türü ayırt etmiyor. Ben türünden devralan yerine düşündü:
//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)
Aynı sorun.
#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);
}
hataları derleme:
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)
^
Görünüşe BOOST_STRONG_TYPEDEF sadece ilkel türleri ile çalışan boost baktığımızda
, Ben güçlü typedef denemek düşündük.
//I want the functionality, but these are NOT the same type!
class Gadget: public Widget{
operator Widget() = delete;
};
da işe yaramadı:
tekrar devralma, ama örtük dönüştürme durdurmaya çalıştı.
Sorular:
- Neden strong_typedef sadece ilkel türleri üzerinde çalışmak artırmak geliyor?
- Güçlendirmek için benzer bir işlev almak için ilkel olmayan bir türü nasıl yazabilirim? Bazı özel miras ve bazı
using
s kullanıyor olabilirsiniz?
Sanırım WidgetBase sınıfını kullanacağım ve sınıf Widget'ını yapacağım: public WidgetBase; sınıf Gadget: genel WidgetBase'. – xis
@zneak: Bu, BOOST_STRONG_TYPEDEF'in yaptığı şeydir. – Deduplicator
@Deduplicator Uygulamaya bakıldığında strong_typedef bir miras değil, bir üyeyi kullanıyor. – pmr