成员函数模板分别定义

问题描述

我在源和标头中声明的类的成员函数模板为

// c.h
class C {
    public:
    C(){}
    template<typename T> 
    C& operator>>(T& obj);
};

// c.cpp
#include <iostream>
#include "c.h"

template<typename T>
C& C::operator>>(T& obj) {
    std::cin >> obj;
    return *this;
}

文件位于一个单独的文件中,如下所示:

#include <iostream>
#include "c.h"

int main() {
    C c;
    int n;
    c >> n;
    std::cout << n << std::endl;
}

编译这些会导致链接错误

/usr/bin/ld: /tmp/ccY8edlI.o: in function `main':
main.cpp:(.text+0x23): undefined reference to `C& C::operator>><int>(int&)'
collect2: error: ld returned 1 exit status`

但是将>>的定义从c.cpp移到主要编译成功的文件中。什么规则导致它在第一种情况下失败?我环顾四周,发现的唯一相关内容是有关MS docs Local classes are not allowed to have member templates.的声明,我不确定是什么本地类,但这听起来与我所拥有的相反。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...