首页 > 解决方案 > 从类对象访问模板参数

问题描述

我在 myclass.hpp 中有一个类模板:

template<class T, class P>
class myclass
{
....
};

在我的 main.cc 中,我创建了一个类的对象:

myclass<int, double> mc;
otherfunc<myclass>(mc);

在其他一些头文件 header1.hpp 中:

template<class MyClass>
void otherfunc(MyClass const &mc)
{
/* Access through 'mc' the underlying template parameters T and P*/
}

如何访问 header1.hpp 中的模板参数 T 和 P?

标签: c++templatesclass-template

解决方案


如何访问 header1.hpp 中的模板参数 T 和 P?

在您的类中提供public类型定义myclass

template<class T, class P>
class myclass
{
public:
     typedef T T_type;
     typedef P P_type;
....
};

因此,您可以访问这些类型

typename myclass::T_Type x;
typename myclass::P_Type y;

别处。


推荐阅读