该代码进行编译(Visual Studio 2013)。请注意,我在类定义之外的函数体中将Set
而不是Set<T>
传递为operator =的参数。但是我不能返回Set
或让它成为Set
的成员;它必须返回Set<T>
并是Set<T>
的成员。
遗漏模板参数在哪里合法? Inside the class definition,还有其他地方?
这是标准的变更吗?我正在尝试与所有现有版本(包括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;
}
最佳答案
类名称在类作用域中可用。并且在单独的成员定义中,一旦您通过了C++ 03返回类型规范和函数名称,就可以进入类范围。因此,这在C++ 03中是可以的:
template< class T >
Set<T> const& Set<T>::operator=( Set const& rhs )
这在C++ 11中是可以的:
template< class T >
auto Set<T>::operator=( Set const& rhs) -> Set const&
这实际上与模板没有任何关系,但是与访问在类范围内可用的名称有关。
例如,在C++ 03中,您必须编写
struct S
{
struct Inner {};
Inner foo();
};
S::Inner S::foo() { return Inner(); }
而在C++ 11及更高版本中,您可以编写
struct S
{
struct Inner {};
auto foo() -> Inner;
};
auto S::foo() -> Inner { return {}; }
除其他外,这是一个很好的理由,它采用尾随返回类型语法作为单个语法约定。
不管哪个年份的标准,在C或C++中This都不行:
void main() //! NOT VALID.
关于c++ - 在类定义之外的模板类成员函数主体中,何时需要模板参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36653459/