在class定义外的模板class成员函数体中,什么时候需要模板参数?
In template class member function body outside class definition, when are template parameters required?
此代码编译(Visual Studio 2013)。请注意,我在 class 定义之外的函数体中将 Set
作为参数传递给 operator=,而不是 Set<T>
。但是我不能 return Set
或者让它成为 Set
的成员;它必须 return 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;
}
class 名称在 class 范围内可用。在单独的成员定义中,一旦您通过了 C++03 return 类型规范和函数名称,您就在 class 范围内。因此,这在 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&
这实际上与模板没有任何关系,但它与访问 class 范围内可用的名称有关。
例如,在 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 {}; }
这是将尾随 return 类型语法作为单一语法约定的一个很好的理由。
在C和C++中都不行,不管是哪一年的标准:
void main() //! NOT VALID.
此代码编译(Visual Studio 2013)。请注意,我在 class 定义之外的函数体中将 Set
作为参数传递给 operator=,而不是 Set<T>
。但是我不能 return Set
或者让它成为 Set
的成员;它必须 return 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;
}
class 名称在 class 范围内可用。在单独的成员定义中,一旦您通过了 C++03 return 类型规范和函数名称,您就在 class 范围内。因此,这在 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&
这实际上与模板没有任何关系,但它与访问 class 范围内可用的名称有关。
例如,在 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 {}; }
这是将尾随 return 类型语法作为单一语法约定的一个很好的理由。
void main() //! NOT VALID.