16

If you have an opaque pointer typedef, is there a way to dynamically refer to the pointed-to type, say, for use in templates? For instance, say you have something like this:

struct Foo; // Forward declared struct
typedef Foo* FooPtr; // Opaque pointer

Because the smart pointer types are templates in terms of the pointer-to type, to define a std::shared_ptr of this, it seems that you have to say:

std::shared_ptr<struct Foo> theSharedPtr;

Is there any way to define such a pointer without "manually" unwrapping the opaque pointer typedef? I feel like I must be missing something obvious here, but you might imagine something like these (note: these do not work):

std::shared_ptr<*FooPtr> theSharedPointer;
// or
std::shared_ptr<pointedto(FooPtr)> theSharedPointer;

I feel like this should be possible. Am I missing something? I feel like this is an impending forehead-smacking moment...

EDIT: Noodling around some more, it appears that, in the common case, shared_ptr<T> wants to take the sizeof(T). You can get around this by providing a deleter to the constructor. I suspect this makes this a bit of an edge case, but it still seems like with all the type wrangling in C++, I should be able to "unwrap" a pointer type without doing so by hand.

3 Answers 3

23

In C++11:

#include <type_traits>

typedef std::shared_ptr< std::remove_pointer< FooPtr >::type > theSharedPtr;

In C++03 you can use boost::remove_pointer in the exact same way.

If you don't want to include boost, writing a remove_pointer metafunction is quite easy:

template<class T> struct remove_pointer;
template<class T> struct remove_pointer<T*> { typedef T type; };
2
  • 3
    Well considering you are using std::shared_ptr is obvious that you are in C++11... I'll leave the rest of my answer here anyway.
    – sbabbi
    Apr 3, 2014 at 13:33
  • I like the completeness of the answer. Apr 3, 2014 at 13:33
5

Yes, since you are already using C++11 features, you can do this with type traits. Specifically by using std::remove_pointer:

std::remove_pointer<Foo*>::type; // Foo

Of course you'll need to include the specific standard header which is:

#include <type_traits>

to use it.

2

Is there any way to define such a pointer without "manually" unwrapping the opaque pointer typedef?

#include <type_traits>
std::shared_ptr<std::remove_pointer<FooPtr>::type> theSharedPointer;

it appears that, in the common case, shared_ptr<T> wants to take the sizeof(T).

It (probably) doesn't need the size; but its initialisation needs to create a deleter, for which the type needs to be complete.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.