4

I am trying to code a toy program to exercise C++, but I got a weird undefined reference error that I can not solve.

My code consists of 3 file:

ex13_6.h:

#include<vector>

namespace ex13_6 {
    template<class T> class Cmp {
    public:
        static int eq(T a, T b) {return a == b;}
        static int lt(T a, T b) {return a < b;}
    };

    template<class T, class C = Cmp<T> > void bubble_sort(std::vector<T> &v);
}

ex13_6.cpp

#include<vector>
#include"ex13_6.h"

namespace ex13_6 {
    template<class T, class C = Cmp<T> > void bubble_sort(std::vector<T> &v) {
        int s = v.size();
        T swap;
        for (int i=0; i<s; i++) {
            for (int j=0; j<s; j++) {
                if (C::lt(v.at(j), v.at(i))) {
                    swap = v.at(i);
                    v.at(i) = v.at(j);
                    v.at(j) = swap;
                }
            }
        }
    }
}

main.cpp:

#include"ex13_6.h"
#include<iostream>
#include<vector>

using namespace std;
using namespace ex13_6;

int main() {
    // Sort using default comparison for int
    vector<int> v_int;
    for (int i=0; i<10; i++) {
        v_int.push_back(10-i);
    }
    bubble_sort(v_int);
    cout << "sort of int vector:\n";
    for (vector<int>::const_iterator it = v_int.begin(); it != v_int.end(); it++) {
        cout << ' ' << *it;
    }
    cout << '\n';
}

And I am compiling using:

g++ main.cpp -o main -std=gnu++0x ex13_6.cpp

Here is the error message:

/tmp/ccRwO7Mf.o: In function `main':
main.cpp:(.text+0x5a): undefined reference to `void ex13_6::bubble_sort<int, ex13_6::Cmp<int> >(std::vector<int, std::allocator<int> >&)'
collect2: ld returned 1 exit status

I really appreciate any help!

4

3 回答 3

3

bubble_sort模板的实现移动到头文件中。

模板不像 Java 中的泛型,所有的魔法都发生在 C++ 的编译时。为了让编译器为每个模板实例化生成代码,它必须是可见的,并且要做到这一点,它必须在头文件(或其他文件)中并包含在使用它的每个翻译单元中。

于 2013-04-30T20:18:43.510 回答
1

您的模板函数定义应该在 ex13_6.h 文件中:

#include<vector>

namespace ex13_6 {
    template<class T> class Cmp {
    public:
        static int eq(T a, T b) {return a == b;}
        static int lt(T a, T b) {return a < b;}
    };

    template<class T, class C = Cmp<T> > void bubble_sort(std::vector<T> &v) {
        int s = v.size();
        T swap;
        for (int i=0; i<s; i++) {
            for (int j=0; j<s; j++) {
                if (C::lt(v.at(j), v.at(i))) {
                    swap = v.at(i);
                    v.at(i) = v.at(j);
                    v.at(j) = swap;
                }
            }
        }
    }
}
于 2013-04-30T20:14:06.283 回答
0

您需要将模板实现放在头文件中。

实例化模板时,编译器需要“查看”实现,因此如果您只包含标头,则实现需要在那里。

不要包含 .cpp 文件。

于 2013-04-30T20:19:19.570 回答