从指针typedef指向const对象

时间:2015-09-01 07:09:33

标签: c++ typetraits

想象一下情况

struct Foo{};

typedef Foo* FooPtr;

当我们只访问FooPtr而不是Foo时(例如类定义了这样的公共typedef)

然后我们想要制作const Foo pointers的容器。不是const pointers to Foo objects的容器(被禁止)

所以我无法做到

std::vector<const FooPtr> v;    
//gives
//std::vector<Foo * const, std::allocator<Foo * const> >

C ++为这种情况提供了什么? (我知道这是更多的设计问题,类Foo应该提供更好的typedef,或者它不打算像我想的那样使用它)

我提出的唯一解决方案是

std::vector<const std::remove_pointer<FooPtr>::type *> vv; 
//gives
//std::vector<Foo const *, std::allocator<Foo const *> >

或者写得更好(并且命名很差(任何名字建议?))作为特征:

template <typename T>
struct add_const_ignore_ptr
{
    typedef typename const std::remove_pointer<T>::type * type;
};

一样使用
typedef add_const_ignore_ptr<FooPtr>::type ConstFooPtr;

std::vector<ConstFooPtr> vvv;

有更好的选择吗?

1 个答案:

答案 0 :(得分:3)

您可以忽略给定的typedef,为Foo执行前向声明并定义自己的typedef。

struct Foo;

using MyConstFooPtr = const Foo*;

std::vector<MyConstFooPtr> myVec;

修改 正如西蒙所说,另一种解决方案是必要的。您可以利用'decltype'来推断出您需要的类型信息:

//
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;
}