Reputation: 7834
Imagine a situation
struct Foo{};
typedef Foo* FooPtr;
when we have access only to FooPtr
not Foo (for example class defines such public typedef)
Then we want to make container of const Foo pointers
. Not container of const pointers to Foo objects
(which is forbidden)
So I can't do
std::vector<const FooPtr> v;
//gives
//std::vector<Foo * const, std::allocator<Foo * const> >
What C++ offers for this situations? (I know it is more design issue, class Foo should offers better typedef, or it is not intended to use it like I want)
The only solution I came up with is
std::vector<const std::remove_pointer<FooPtr>::type *> vv;
//gives
//std::vector<Foo const *, std::allocator<Foo const *> >
or more nicely written (and very poorly named (any name suggestions?)) as trait:
template <typename T>
struct add_const_ignore_ptr
{
typedef typename const std::remove_pointer<T>::type * type;
};
used like
typedef add_const_ignore_ptr<FooPtr>::type ConstFooPtr;
std::vector<ConstFooPtr> vvv;
Is there a better option?
Upvotes: 2
Views: 86
Reputation: 111
You can ignore the given typedef, do a forward declaration for Foo and define an own typedef.
struct Foo;
using MyConstFooPtr = const Foo*;
std::vector<MyConstFooPtr> myVec;
edit: As Simon stated out, another solution is necessary. You could exploit 'decltype' to deduce the type information you need:
//
class Test
{
private:
struct Foo { int a; };
public:
typedef Foo* FooPtr;
};
//
template<typename T>
const T* toConst(T);
//
int main()
{
std::vector<decltype(toConst(*Test::FooPtr()))> myVec;
return 0;
}
Upvotes: 3