如何使此模板类编译

How to get this template class to compile?

本文关键字:编译 何使此      更新时间:2023-10-16

对不起,我无法提出一个可以正确捕获我的问题的问题。我的问题是。

我有这样的模板类。我无法理解如何确切定义GET函数。

template<class Data>
class Class
{
    struct S
    {
    };
    void Do();
    S Get();
};
template<class Data>
void Class<Data>::Do()
{
}
template<class Data>
Class<Data>::S Class<Data>::Get()
{
}

我得到以下错误

1>error C2143: syntax error : missing ';' before 'Class<Data>::Get'
1>error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>fatal error C1903: unable to recover from previous error(s); stopping compilation
template<class Data>
Class<Data>::S Class<Data>::Get()

需要

template<class Data>
typename Class<Data>::S Class<Data>::Get()

因为 S是一个因类型。每当您有嵌套在模板中的类型时,都需要使用关键字typename。例如,vector<int>上的迭代器具有typename vector<int>::iterator类型。

a c 11样式,易于读写:

template<class Data>
auto Class<Data>::Get() -> S {
    return {};
}