开发者

Class type from pointer used as template argument

If a pointer to an user defined type is passed as template argument to a template class, is it possible to get the class type of the argument?

template <class T> struct UserType {
    typedef T value_type;
    ...
};

int main () {
    typedef std::vector<开发者_高级运维;UserType<double>*> vecType
    vecType vec;

    vecType::value_type::value_type m; //how to get the double here?

    return 0;
}


Use traits:

template <typename> struct ptr_traits {};
template <typename T> struct ptr_traits<T*>
{ typedef T value_type; };

ptr_traits<vecType::value_type>::value_type m;


Use boost::remove_pointer.


Traits are probably the way to go here.

Alternatively, you could introduce another typedef and use this in the declaration of vecType and m:

typedef UserType<double>* UserTypeDoublePtr;
typedef std::vector<UserTypeDoublePtr> vecType;

UserTypeDoublePtr m;


Let me ask you what do you mean by "getting" the type?

You can actually use this type, for instance you may declare new variables of this type (as you demonstrate in your example), without explicitly specifying it.

Do you mean you want a textual description of the type?

If this is the case - there's no generic 100%-working way of doing it. This is because after compilation + link type and variable/function names vanish. They just don't exist at runtime.

You may however write some extra code to get the textual description of the types you need. One of the ways to do this:

template <typename T> const char* TypeName();
template <> const char* TypeName<int>() { return "int"; }
template <> const char* TypeName<double>() { return "double"; }
// ...

You'll get a linker error if you try to use TypeName on a type whose name you didn't yet define. Then you'll have to add the appropriate template specialization of TypeName.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜