我在工作中看到了下面这段代码
typedef int real_type;
typedef vector<int> vector_type;
template <class ASD> class program_class
{
public:
typename ASD::vector_type member_func();
};
template <typename ASD> typename ASD::real_type program_class<ASD>::member_func()
{
typedef typename ASD::real_type R;
typedef typename ASD::vector_type V;
return 123;
}
从概念上讲,我不明白如何像这样声明返回类型:typename ASD::real_type
。原则上,这要求我们实例化 ASD
的类型是一个 typedef 类,对吧?
我可以看一下这是如何实现的示例吗?
最佳答案
全局 vector_type
在全局命名空间中。如果您使用范围运算符 ::
范围将更改为范围运算符的左侧,对于模板,范围是 ASD
而不再是全局范围.
这意味着,正如您所注意到的,ASD
类(无论是什么)必须在其中定义了自己的 vector_type
和 real_type
, 否则编译器会给你一个错误。
例子:
typedef int real_type; // The global type alias
...
struct Foo
{
typedef long real_type; // The local type alias
...
};
program_class<Foo> my_program_object;
现在在 program_class
中,real_type
将是 Foo::real_type
而不是全局的 ::real_type
.
正如您在我的示例中看到的那样,您可以使用不同的基本类型,因为这两种类型的别名彼此完全分开。
关于c++ - 类型定义类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20002877/