C++ 从指针typedef生成指向常量对象的指针

C++ 从指针typedef生成指向常量对象的指针,c++,typetraits,C++,Typetraits,想象一种情况 struct Foo{}; typedef Foo* FooPtr; 当我们只能访问FooPtr而不能访问Foo时(例如类定义了这样的公共typedef) 然后我们要制作常量Foo指针的容器。不是指向Foo对象的常量指针的容器(这是禁止的) 所以我做不到 std::vector<const FooPtr> v; //gives //std::vector<Foo * const, std::allocator<Foo * const> &g

想象一种情况

struct Foo{};

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

然后我们要制作
常量Foo指针的容器。不是指向Foo对象的
常量指针的容器(这是禁止的)

所以我做不到

std::vector<const FooPtr> v;    
//gives
//std::vector<Foo * const, std::allocator<Foo * const> >
std::vector v;
//给予
//向量

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

我想出的唯一解决办法是

std::vector<const std::remove_pointer<FooPtr>::type *> vv; 
//gives
//std::vector<Foo const *, std::allocator<Foo const *> >
std::向量vv;
//给予
//向量
或者写得很好(而且名字很差(有名字建议吗?):

template <typename T>
struct add_const_ignore_ptr
{
    typedef typename const std::remove_pointer<T>::type * type;
};
模板
结构添加\u常量\u忽略\u ptr
{
typedef typename const std::remove_pointer::type*type;
};

typedef add_const_ignore_ptr<FooPtr>::type ConstFooPtr;

std::vector<ConstFooPtr> vvv;
typedef add_const_ignore_ptr::type ConstFooPtr;
std::矢量vvv;

是否有更好的选项?

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

struct Foo;

using MyConstFooPtr = const Foo*;

std::vector<MyConstFooPtr> myVec;
structfoo;
使用MyConstFooPtr=constfoo*;
std::载体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;
}
//
课堂测试
{
私人:
结构Foo{int a;};
公众:
类型定义Foo*FooPtr;
};
//
模板
常数T*toConst(T);
//
int main()
{
std::载体myVec;
返回0;
}
Quote:when我们只能访问FooPtr而不能访问Foo(例如类定义了这样的公共typedef),那么如果您有这样的
类测试{private:struct Foo{int a;};public:typedef Foo*FooPtr;}您的解决方案无法工作。