Template typedefs - What's your work around?

C++TemplatesType Safety

C++ Problem Overview


C++ 0x has template aliases (sometimes referred to as template typedefs). See here. Current spec of C++ does not.

What do you like to use as work around ? Container objects or Macros ? Do you feel its worth it ?

C++ Solutions


Solution 1 - C++

> What do you like to use as work around ? Container objects or Macros ? Do you feel its worth it ?

The canonical way is to use a metafunction like thus:

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

// Invoke:

my_string_map<int>::type my_str_int_map;

This is also used in the STL (allocator::rebind<U>) and in many libraries including Boost. We use it extensively in a bioinformatical library.

It's bloated, but it's the best alternative 99% of the time. Using macros here is not worth the many downsides.

(EDIT: I've amended the code to reflect Boost/STL conventions as pointed out by Daniel in his comment.)

Solution 2 - C++

> template > struct my_string_map : public std::map > { > };

You shouldn't inherit from classes that do not have a virtual destructor. It's related to destructors in derived classes not being called when they should be and you could end up with unallocated memory.

That being said you could probably get away with it in the instance above because you're not adding any more data to your derived type. Note that this is not an endorsement. I still advice you don't do it. The fact that you can do it doesn't mean you should.

EDIT: Yes, this is a reply to ShaChris23's post. I probably missed something because it showed up above his/her message instead of below.

Solution 3 - C++

Sometimes you can just explicitly write out the untemplated typedefs for all the necessary types. If the base class is templated on multiple template args with only one type desired to be typedefed you can inherit a specialized class with typedef effectively included in the inherited class name. This approach is less abstruse than the metafunction approach.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGeorge GodikView Question on Stackoverflow
Solution 1 - C++Konrad RudolphView Answer on Stackoverflow
Solution 2 - C++xghostView Answer on Stackoverflow
Solution 3 - C++Andrei PokrovskyView Answer on Stackoverflow