Typedefs templates - What is your job?

C ++ 0x has template aliases (sometimes called typedefs). See here . There is no current C ++ specification.

What do you like to use as work? Container objects or macros? Do you think it's worth it?

+71
c ++ type-safety templates
Aug 25 '08 at 14:47
source share
3 answers

What do you like to use as work? Container objects or macros? Do you think it's worth it?

The canonical way is to use a metapound similar in this way:

template <typename T> struct my_string_map { typedef std::map<std::string, T> type; }; // Invoke: my_string_map<int>::type my_str_int_map; 

It is also used in STL ( allocator::rebind<U> ) and in many libraries, including Boost. We widely use it in the bioinformation library .

It is bloated, but it is the best alternative in 99% of cases. Using macros here is not worth the many flaws.

(EDIT: I amended the code to reflect Boost / STL agreements, as Daniel pointed out in his comment.)

+102
Aug 25 '08 at 14:51
source share
 template <typename T> struct my_string_map : public std::map<std::string,T> { }; 

You should not inherit from classes that do not have a virtual destructor. This is due to destructors in derived classes that are not called when they should be, and you could get unallocated memory.

Having said that, you might just avoid it in the above instance, because you are not adding more data to your derived type. Please note that this is not an endorsement. I still advise you not to do this. The fact that you can do this does not mean that you should.

EDIT: Yes, this is a response to the ShaChris23 post. I probably missed something because it appeared above his / her message and not below.

+10
Jan 18 '10 at 23:01
source share

Sometimes you can just explicitly write out unused typedefs for all the types you need. If the base class is templated in several template arguments with only one type, which is required for typedefed, you can inherit a specialized class with typedef, which is effectively included in the name of the inherited class. This approach is less abstruse than the metapound approach.

0
Mar 19 '13 at 0:31
source share



All Articles