views:

168

answers:

3

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.

Its tedious typing tr1::shared_ptr<const U> or 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?

+1  A: 
using tr1::shared_ptr;

should allow you to use shared_ptr without prefix, but that's all I know. Sorry.

roe
Since my templated definitions and declarations have to be in a header file, won't this violate the rule that one should not have a using declaration in a header file ?
@user231536: I don't see why it would HAVE to go in the header file, you can just put it in your source file? It would have to be done in all source files, but would reduce the clutter nonetheless.
roe
+2  A: 

Nothing to reduce verbosity (except what roe says).

But nice article on problem itself: Template 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!).

Alexander Poluektov
+8  A: 

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.

C++0x has template typedefs, you could check whether your compiler can be persuaded to accept them:

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

Then say 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. Or if you're using it in a narrow enough context that a macro isn't scary.

Steve Jessop
The inner type is nice, but it hardly makes the code less verbose...
UncleBens
Well, it does a bit in contexts where you don't need `typename`. Otherwise, no, it's not great for something as short as `tr1::shared_ptr<U>`. If it was `std::vector<shared_ptr<U> >::const_iterator` that needed abbreviation, then we might be in business :-)
Steve Jessop