简体   繁体   English

如何获得此模板类进行编译?

[英]How to get this template class to compile?

Sorry, I couldn't frame a question that could capture my problem properly. 抱歉,我无法提出一个可以正确解决我的问题的问题。 My problem is this. 我的问题是这个。

I have a templated class like this. 我有这样的模板化类。 I am not able to understand how exactly to define the Get function. 我不明白如何准确定义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()
{
}

I get the following errors 我收到以下错误

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()

needs to be 需要是

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

because S is a dependent type. 因为S是从属类型。 Any time you have a type that's nested in a template you need to use the keyword typename . 每当您将某个类型嵌套在模板中时,都需要使用关键字typename For example, an iterator over a vector<int> has the type typename vector<int>::iterator . 例如,在vector<int>上的typename vector<int>::iterator的类型类型为typename vector<int>::iterator

A C++11 style, easier to read and write : C ++ 11样式,更易于阅读和编写:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM