Experience with C + + templates (traits) in the "C + + Template Tour" project-new annotations

Source: Internet
Author: User
Tags traits

Questions and Requirements:

Please read this article first, theexperience of utilizing C + + template (traits) in the "C + + Templates Tour" project. For the questions raised in this article, I give a new idea.

Talking is cheap,show me the code.

Code:
classexportdata{Union {string*sp; Long*LP; Double*DP; void*VP;    }; enumMy_type {SP,LP,DP} types; StaticUnordered_map<type_index,my_type>Typemap; Public: Template<typename t>ExportData (T t) {if(Typemap.find (typeID (t)) = =typemap.end ()) Assert (false); VP=NewT (t); Types=Typemap[typeid (T)]; } template<typename t>voidSetData (T t) {if(Typemap.find (typeID (t)) = =typemap.end ()) Assert (false); Switch(types) { CaseSp:delete SP;  Break;  CaseDp:delete DP;  Break;  CaseLp:delete LP;  Break; } VP=NewT (t); Types=Typemap[typeid (T)]; } template<typename t>voidGetData (t&t) {if(Typemap[typeid (T)]!=types) assert (false); T=* (static_cast<t*>(VP)); } }; Unordered_map<type_index,ExportData::my_type>exportdata::typemap{{typeid (string), exportdata::my_type::sp}, {typeid (Long), Exportdata::my_type::lp}, {typeid (Double), Exportdata::my_type::D P},};

Repeat, four-point requirement:

1. ExportData needs to support only integer (long), floating-point (double), String, and binary (void*, size) 4 types of Operations . ( I did not consider the binary) 2. ExportData need to consider the size of the structure and minimize the space redundancy (I use a union to hold pointers to various types of data ) 3. Even if you operate on the above 4 different data types, you want to is used) 4. When the caller tries to use a data type other than the above 4 types, the caller is able to know the type mismatch by returning an error ( attempting to use other types will cause the assertion to fail and terminate the operation for demonstration purposes)

If you also hate the presence of Swtich in your code, you can use the table-driven method again. The code looks like this :
classdeletelong{ Public:    void operator()(void*p) {Delete static_cast<Long*>(P); }};classdeletestring{ Public:    void operator()(void*p) {Delete static_cast<string*>(P); }};classdeletedouble{ Public:    void operator()(void*p) {Delete static_cast<Double*>(P); }}; classexportdata{Union {string*sp; Long*LP; Double*DP; void*VP;    }; enumMy_type {SP,LP,DP} types;//Change the it to object.    StaticUnordered_map<type_index,my_type>Typemap; Staticvector<function<void(void*) >>deleters; Public: Template<typename t>ExportData (T t) {if(Typemap.find (typeID (t)) = =typemap.end ()) Assert (false); VP=NewT (t); Types=Typemap[typeid (T)]; } template<typename t>voidSetData (T t) {if(Typemap.find (typeID (t)) = =typemap.end ()) Assert (false); (Deleters[types])        (VP); VP=NewT (t); Types=Typemap[typeid (T)]; } template<typename t>voidGetData (t&t) {if(Typemap[typeid (T)]!=types) assert (false); T=* (static_cast<t*>(VP)); }
This can be changed to overloaded, void GetData (long& t) {...} void GetData (sting& t) {...} void GetData (double& t) {...} Call other type to compile error}; Unordered_map<type_index,ExportData::my_type>exportdata::typemap{{typeid (string), exportdata::my_type::sp}, {typeid (Long), Exportdata::my_type::lp}, {typeid (Double), Exportdata::my_type::D p},};vector<function<void(void*) >> ExportData::d eleters {deletestring (), Deletelong (), Deletedouble (),};

Here is the test code:

intMain () {LongI=5; Longj=0; strings="Hello"; stringSS;    ExportData p (i); P.setdata (++i);    P.getdata (j);    P.setdata (s);    P.getdata (ss); cout<<j<<Endl; cout<<ss<<Endl; return 0;}

The additional benefits of this code : 1.CodeShorter and more compact. (Reduced code volume)
2.ExportData objects are easier to use.。
3. ExportDataobjects have only two data, one is a pointer union, and the other is an enumeration value. (Better performance)
4. I added an additional feature on the basis of the author's request for 4 points, and ExportData can dynamically change the type of data held . (more powerful)
5. All of the methods in a class use overloading instead of using a template, although it can lead to a large increase in code, but the advantage is that we can prompt the user ExportData at compile time to not support certain types, but also to improve a bit of runningSpeed。 Do you want to do this,Specific problems can be analyzed concretely.
6.Because of the use of templates, scalability is strong when addedWhen supporting types, you only need to change a small amount of code . (Extensibility is better)

Finally, this code is a sample code that may not withstand scrutiny , then quoting the original author, " I think there is a better way to do this, such as to try to prompt at compile time when the hint type is not supported but not at run time by returning an error." If there is a better solution, you are welcome to discuss it together. ",ME TOO.

Experience with C + + templates (traits) in the "C + + Template Tour" project-new annotations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.