[英]In template class member function body outside class definition, when are template parameters required?
This code compiles (Visual Studio 2013). 该代码进行编译(Visual Studio 2013)。 Note that I pass in Set
, not Set<T>
, as a parameter to operator=, in the function body which is outside the class definition. 请注意,我在类定义之外的函数体中将Set
而不是Set<T>
作为参数传递给operator =。 But I can't return Set
or have it be a member of Set
; 但是我不能返回Set
或让它成为Set
的成员; it must return Set<T>
and be a member of Set<T>
. 它必须返回Set<T>
和成为其成员Set<T>
Where is it legitimate to leave out the template parameters? 遗漏模板参数在哪里合法? Inside the class definition , and where else? 在类定义内 ,还有其他地方?
Is this a change in the standard? 这是标准的变更吗? I'm trying to maintain compatibility with all existing versions, including 98. 我正在尝试与所有现有版本(包括98)保持兼容性。
template <typename T>
class Set
{
public:
Set() {}
const Set& operator=(const Set& rhs);
//Shouldn't this have to be
//const Set<T>& operator= (const Set<T>& rhs); ?
};
template <typename T>
const Set<T>& Set<T>::operator= (const Set& rhs) //<-- HERE
{
Set temp; //<-- AND HERE
/* ... */
return *this;
}
int main()
{
Set<int> S, T;
T = S;
}
The class name is made available in the class scope. 类名称在类作用域中可用。 And in a separate member definition, once you've passed the C++03 return type specification and the function name, you're in class scope. 并且在单独的成员定义中,一旦您通过了C ++ 03返回类型规范和函数名称,就可以进入类范围。 Thus, this is OK in C++03: 因此,这在C ++ 03中是可以的:
template< class T >
Set<T> const& Set<T>::operator=( Set const& rhs )
And this is OK in C++11: 这在C ++ 11中是可以的:
template< class T >
auto Set<T>::operator=( Set const& rhs) -> Set const&
This doesn't really have anything to do with templates, but it has to do with accessing a name that's available in class scope. 这实际上与模板没有任何关系,但是与访问在类范围内可用的名称有关。
For example, in C++03 you'd have to write 例如,在C ++ 03中,您必须编写
struct S
{
struct Inner {};
Inner foo();
};
S::Inner S::foo() { return Inner(); }
while with C++11 and later you can write 而在C ++ 11及更高版本中,您可以编写
struct S
{
struct Inner {};
auto foo() -> Inner;
};
auto S::foo() -> Inner { return {}; }
which is one good reason, among many others, to adopt the trailing return type syntax as a single syntax convention. 除其他外,这是一个很好的理由,它采用尾随返回类型语法作为单个语法约定。
This is not OK in either C or C++, regardless of which year's standard: 这是不是在C或C OK ++,无论哪一年的标准:
void main() //! NOT VALID.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.