c++ - 在类定义之外的模板类成员函数主体中,何时需要模板参数?

标签 c++ c++98

该代码进行编译(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/

相关文章:

c++ - 读取文件时字符缓冲区溢出

c++ - const-promotion 在哪里定义

c++ - 从 vector 中删除一对并为 vector 对保留空间

c++ - 如何在线程之间共享一个全局对象?

c++ - 清除 cout 缓冲区 (c++)

android - 创建安卓应用

c++ - 共享对象文件应该放在哪里?

c++ - 无法理解此语句 - 运算符后的返回类型

c++ - std::string 到 uint64_t

c++ - 仅当某个函数后跟另一个函数时才允许调用它