简体   繁体   English

C ++模板化typedef

[英]C++ templated typedef

I have a templated class 我有一个模板课

template <T>
class Example 
{
...
};

inside which there are many methods of the following type: 其中有许多类型的方法:

template <class U> <class V> method(....)

Inside these I use tr1::shared_ptr to U or V or T. 在这些内部我使用tr1 :: shared_ptr到U或V或T.

Its tedious typing tr1::shared_ptr<const U> or tr1::shared_ptr<const V> . 它繁琐的输入tr1::shared_ptr<const U>tr1::shared_ptr<const V>

The obvious thing to do: 显而易见的事情:

template <typename U>
typedef tr1::shared_ptr<U> shptr<U>;

does not work. 不起作用。

What do you do in this situation? 你在这种情况下做了什么? Anything that can reduce verbosity? 什么能减少冗长的东西?

You can use an inner type: 您可以使用内部类型:

template <typename U>
struct sptr {
    typedef tr1::shared_ptr<U> t;
};

Then say sptr<U>::t , or unfortunately often typename sptr<U>::t . 然后说sptr<U>::t ,或者不幸的是经常typename sptr<U>::t

C++0x has template typedefs, you could check whether your compiler can be persuaded to accept them: C ++ 0x有模板typedef,您可以检查是否可以说服您的编译器接受它们:

template<typename U>
using sptr = tr1::shared_ptr<U>;

Then say sptr<U> 然后说sptr<U>

And of course there's always #define sptr ::tr1::shared_ptr , for example if you're expecting C++0x in future and want to bridge the gap. 当然,总是有#define sptr ::tr1::shared_ptr ,例如,如果您将来期待C ++ 0x并希望缩小差距。 Or if you're using it in a narrow enough context that a macro isn't scary. 或者,如果你在一个足够狭窄的环境中使用它,那么宏并不可怕。

Nothing to reduce verbosity (except what roe says). 没有什么可以减少冗长(除了roe说的)。

But nice article on problem itself: Template Typedef . 但关于问题本身的好文章: 模板Typedef

You would really need this trick if you have some generic function that expects your type to have some associated typedef, and your type is templated (consider that you have provide result_t and it should be your template parameter!). 如果你有一个期望你的类型有一些相关的typedef一些通用的功能,和你的类型模板,你确实需要这一招(认为你有提供result_t,它应该是你的模板参数!)。

using tr1::shared_ptr;

should allow you to use shared_ptr without prefix, but that's all I know. 应该允许你使用不带前缀的shared_ptr ,但这就是我所知道的。 Sorry. 抱歉。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM