C++ 模板 typedefs - 你的工作是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26151/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Template typedefs - What's your work around?
提问by George Godik
回答by Konrad Rudolph
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.
这也用于 STL ( allocator::rebind<U>
) 和许多库,包括 Boost。我们在生物信息库中广泛使用它。
It's bloated, but it's the best alternative 99% of the time. Using macros here is not worth the many downsides.
它很臃肿,但在 99% 的情况下都是最好的选择。在这里使用宏是不值得的。
(EDIT: I've amended the code to reflect Boost/STL conventions as pointed out by Daniel in his comment.)
(编辑:我已经修改了代码以反映 Daniel 在评论中指出的 Boost/STL 约定。)
回答by xghost
template <typename T> struct my_string_map : public std::map<std::string,T> { };
template <typename T> struct my_string_map : public std::map<std::string,T> { };
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'tdo it. The fact that you cando 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.
编辑:是的,这是对 ShaChris23 帖子的回复。我可能错过了一些东西,因为它出现在他/她的消息上方而不是下方。
回答by Andrei Pokrovsky
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.
有时,您可以为所有必需的类型明确写出未模板化的 typedef。如果基类在多个模板 args 上模板化,并且只有一种类型需要 typedef,您可以继承一个专门的类,typedef 有效地包含在继承的类名中。这种方法没有元函数方法那么深奥。