c++ - 在显式初始化期间尝试创建函数拷贝时出错

标签 c++ templates generics

我无法理解我在模板类程序中遇到的错误。

代码

#include <iostream>
#include<string>

using namespace std;

template <class dataType> class myClass {
public:
void function();
};

template<> class myClass<int> {
public:
void expli_function();
};

template <class dataType> void myClass<dataType>::function() {
cout << "Not an explicit function !" << endl;
}

template <class int> void myClass<int>::expli_function() { //<-- while pointing towards errors compiler points here
cout << "Explicit function !" << endl;
}

int main() {
myClass<string> ob1;
myClass<int> ob2;
ob1.function();
ob2.expli_function();
} 

错误是:

tester_1.cpp(20): error C2332: 'class' : missing tag name
tester_1.cpp(20): error C2628: '<unnamed-tag>' followed by 'int' is illegal (did you forget a ';'?)
tester_1.cpp(20): error C2993: '' : illegal type for non-type template parameter '<unnamed-tag>'
error C2244: 'myClass<int>::expli_function' : unable to match function definition to an existing declaration

为什么会出现这些错误以及如何解决这些错误?

最佳答案

这解决了它:

void myClass<int>::expli_function() {
    cout << "Explicit function !" << endl;
}

class myClass<int>是一个专业,它不需要template<int>定义函数方法之前的关键字。

关于c++ - 在显式初始化期间尝试创建函数拷贝时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8095166/

相关文章:

c++ - 如何在 for 循环中进行错误捕获

c++ - 读取字符显示所有字符后跟一些垃圾字符

c++ - 传递动态模板参数

java - 重写在父类中为 EntityManager 声明的持久上下文 unitName。

c++ - 如何通过 NCurses 的 C++ 绑定(bind)在屏幕上显示 NCursesPanel

c++ - 关于 C++ 转换问题

c++ - C++ 中带有纯虚方法的抽象模板类

c++ - 共享对象文件中的 undefined symbol

java - 如何解决由 Java 泛型中的交集类型引起的不明确方法?

C# 在运行时从泛型类型查找方法重载