c++ 模板函数声明与定义分离的语法问题
来源:百度知道 编辑:UC知道 时间:2024/06/26 04:32:45
// A.h
#ifndef _A_H
#define _A_H
class A {
public:
template <typename T>
static T max(T a, T b);
};
#endif /* _A_H */
// A.cpp
#include "A.h"
template <typename T>
T A::first(T a, T b) {
return a;
}
// main.cpp
#include "A.h"
int main(int argc, char** argv) {
A::first(1, 2);
return (0);
}
编译通过不了,报错:
undefined reference to `int A::first<int>(int, int)'
不知道模板函数的定义应该怎么写
不好意思,把static T max(T a, T b);
改为static T first(T a, T b); 即使改过后,仍然不行,同样的编译错误
#ifndef _A_H
#define _A_H
class A {
public:
template <typename T>
static T max(T a, T b);
};
#endif /* _A_H */
// A.cpp
#include "A.h"
template <typename T>
T A::first(T a, T b) {
return a;
}
// main.cpp
#include "A.h"
int main(int argc, char** argv) {
A::first(1, 2);
return (0);
}
编译通过不了,报错:
undefined reference to `int A::first<int>(int, int)'
不知道模板函数的定义应该怎么写
不好意思,把static T max(T a, T b);
改为static T first(T a, T b); 即使改过后,仍然不行,同样的编译错误
模板函数声明与定义好像不能分开的
你的类声明中有first这个函数么
A.cpp 加入progma once即可
//给你改了一下
// A.h
#ifndef _A_H
#define _A_H
template <class T>
class A {
public:
static T first(T a, T b);
};
#endif /* _A_H */
// A.cpp
#include "A.h"
template <class T>
T A<T>::first(T a, T b) {
return a;
}
// main.cpp
#include "A.h"
int main(int argc, char** argv) {
A<int>::first(1, 2);
return (0);
}