Martin Drozdik
Martin Drozdik

Reputation: 13313

How to simplify complicated template declarations

For example I would like to simplify the std::tr1::shared_pointer template class. I would like to have an alias for std::tr1::shared_pointer.

But this doesn't work:

#include <tr1/memory>

template <class T>
class SharedPointer : public std::tr1::shared_ptr<T>
{
};

int main(int argc, char *argv[])
{
    SharedPointer<int> test(new int(5));
    return 0;
}

Since the constructors are not inherited.

Is there a pattern to solve this?

Upvotes: 4

Views: 370

Answers (2)

Ken Wayne VanderLinde
Ken Wayne VanderLinde

Reputation: 19349

If you want to alias it, a using declaration will create a true alias, rather than a subclass:

template<class T>
using SharedPointer = std::tr1::shared_ptr<T>;

Edit

A method that should work on GCC 4.6.* compilers would be to make a wrapper function around the std::tr1::shared_ptr<T>. Since GCC 4.6.* supports the C++11 library, I've used that instead of TR1:

#include <memory>
#include <utility>

template<typename T, typename... Args>
std::shared_ptr<T> make_shared_ptr(Args &&... args)
{
    return std::shared_ptr<T>(std::forward<Args>(args)...);
}

int main(int argc, char *argv[])
{
    auto test = make_shared_ptr<int>(new int(5));
    return 0;
}

Upvotes: 7

Edward Loper
Edward Loper

Reputation: 15944

If you're not using C++11, then unfortunately the best you can do is:

template <class T>
struct SharedPointer
{
    typedef std::tr1::shared_ptr<T> type;
};

Which has to be used as:

SharedPointer<int>::type x(new(int));

Upvotes: 5

Related Questions