c++ - 在 C++ 中使用在其他文件中声明的模板

标签 c++ templates

<分区>

Possible Duplicate:
Why can templates only be implemented in the header file?
What is an undefined reference/unresolved external symbol error and how do I fix it?

我在文件中定义了一个模板类。

point.h是

#ifndef POINT_H
#define POINT_H

using namespace std;

template <typename T, int size>
class point {
private:
    T coordinates[size];

public:
    point();
    void set_coordinates(const T *);
    void get_coordinates(T *);
};

#endif  /* POINT_H */

point.c是

#include "point.h"

template <typename T, int size>
point::point() {
    for (int i = 0; i < size; i++)
        coordinates[i] = 0;
}

template <typename T, int size>
void point<T, size>::set_coordinates(const T *coordinates) {
    for (int i = 0; i < size; i++)
        this->coordinates[i] = coordinates[i];
}

template <typename T, int size>
void point<T, size>::get_coordinates(T *coordinates) {
    for (int i = 0; i < size; i++)
        coordinates[i] = this->coordinates[i];
}

我将此模板用作 point<int, 2> p0; .但是编译器给出错误 point<int, 2>没有定义。 我搜索了这个并找到了两个解决方案 - 1. 使用 export多变的。但我读到并非所有编译器都支持它。所以,我不想使用它。 2. 创建明确的类特化,如

template <> class point<int> {
    ...
}

但是没有其他方法可以做到这一点吗? (我的意思是在 C++ 标准容器中,他们可能使用了一些技术来做到这一点。)

最佳答案

阅读这个和接下来的两个常见问题解答 - C++ FAQ

关于c++ - 在 C++ 中使用在其他文件中声明的模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12651848/

相关文章:

C++:需要一个声明

c++ - 使用enable_if来防止声明?

C++ 函数与带有整数参数的模板?

c++ - 我应该总是在头文件中定义我的整个模板类吗?

c++ - 将字符串 "A10"拆分为 char 'A' 和 int 10

c++ - 无法在 Metro Style Project (WINRT) 中使用 opencl

c++ - boost::lexical_cast int 到用零填充的字符串

c++ - 在 OS X 上使用 yaml-cpp 时出现问题

javascript - 我如何在 JQuery 中解决这个问题?

java - 替换 .sql 脚本中的变量并使用 Java JDBC 运行它们