2016-12-15 22 views
0

我有三個C++文件,sort.cpp定義了一個冒泡排序函數,它接受一個數組,一個數組的長度和一個用於比較的函數。 sort.h包含命名空間內的函數原型。 main.cpp用於測試實現。C++鏈接器錯誤:使用函數模板時找不到符號

sort.h:

#ifndef SORT_H 
#define SORT_H 

namespace sort { 
    template <typename T> 
    void bubble(T*, int, bool (*)(T, T)); 
} 

#endif 

sort.cpp:

#include "sort.h" 

template <typename T> 
void sort::bubble(T *array, int length, bool (*compare)(T, T)) { 
    while (length != 0) { 
     int newLength {0}; 
     for (int i {0}; i < length - 1; ++i) { 
      if (compare(array[i], array[i+1])) { 
       T temp {array[i]}; 
       array[i] = array[i+1]; 
       array[i+1] = temp; 
       newLength = i + 1; 
      } 
     } 
     length = newLength; 
    } 
} 

main.cpp中:

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

bool larger(int x, int y) { 
    return x > y; 
} 

int main() { 
    int arr[] {3, 5, 1, 3, 7, 2}; 
    sort::bubble(arr, 6, larger); 
    for(const auto e: arr) 
     std::cout << e << ' '; 
    std::cout << '\n'; 
    return 0; 
} 

當我與g++ main.cpp sort.cpp -std=c++11編譯我的錯誤

Undefined symbols for architecture x86_64: 
    "void sort::bubble<int>(int*, int, bool (*)(int, int))", referenced from: 
     _main in main-767bbd.o 
ld: symbol(s) not found for architecture x86_64 
clang: error: linker command failed with exit code 1 (use -v to see invocation) 

我得到的錯誤是因爲在編譯sort.cpp時編譯器不知道我要使用哪些類型?所以編譯器不會從模板生成任何函數,然後鏈接器在main.cpp中使用它時找不到它?

我該如何解決這個問題?

回答

0

不要爲模板使用兩個文件,只有一個文件:sort.hpp 有一種解決方法,但不推薦。