[英]Declaration of specialized function in template class
我正在努力解決的問題是模板類內部的專用模板函數的聲明(我將類聲明保留在頭文件中,並在關聯的.C文件中定義成員函數)。
我有代表點的模板類。 頭文件如下所示:
//...
template<typename T, int dim=3> // T - coords. type, int dim - no. of dimensions
class Point {
public:
// ...
// function below sets val at the given position in array m_c and returns reference
template<int position> Point& set(T val);
private:
T m_c[dim]; // coordinates
};
//...
功能set
定義位於.C文件中:
template<typename T, int dim> template<int position> Point<T, dim>& Point<T, dim>::set(T val){
// ...
return *this;
}
據我了解,這是其定義的最一般形式。
在主函數中,我創建一個以float
為T
Point
並嘗試在數組中設置一些值:
int main(int argc, char** argv) {
Point<float> p1;
p1.set<0>(3).set<1>(3.6).set<2>(3);
//...
}
為了通過頭文件外部的模板的成員函數的定義使之成為可能,我需要通知編譯器有關.C文件的專門知識:
template class Point<float>;
而且我還需要聲明set函數的用法,我試圖通過這種方式來完成( 而這段代碼就是問題所在 ):
template<> template<int> Point<float>& Point<float>::set(float);
不幸的是,這沒有做,我得到了錯誤:
/tmp/ccR7haA5.o: In function `main':
.../pdim.C:32: undefined reference to `Point<float, 3>& Point<float, 3>::set<0>(float)'
.../pdim.C:32: undefined reference to `Point<float, 3>& Point<float, 3>::set<1>(float)'
.../pdim.C:32: undefined reference to `Point<float, 3>& Point<float, 3>::set<2>(float)'
我真的很感謝可能知道如何解決此問題的人的解釋。 謝謝。
為了在不同的TU中提供功能模板專業化的定義,您需要一個顯式的實例化聲明:
[Point.hpp]
template<typename T, int dim=3>
struct Point
{
template<int position> Point& set(T val);
};
// `extern` makes this an explicit instantiation _declaration_
extern template Point<float,3>& Point<float,3>::set<0>(float);
extern template Point<float,3>& Point<float,3>::set<1>(float);
extern template Point<float,3>& Point<float,3>::set<2>(float);
[Point.cpp]
#include <iostream>
#include "Point.hpp"
template<typename T, int dim>
template<int position>
Point<T,dim>& Point<T,dim>::set(T val)
{
// note: non-standard macro
std::cout << __PRETTY_FUNCTION__ << std::endl;
return *this;
}
// no `extern`: this is an explicit instantiation _definition_
// which instantiates the function template, and therefore requires the definition
// to be available in this TU
template Point<float,3>& Point<float,3>::set<0>(float);
template Point<float,3>& Point<float,3>::set<1>(float);
template Point<float,3>& Point<float,3>::set<2>(float);
[main.cpp中]
#include "Point.hpp"
int main()
{
// in this TU, there's no definition for the function template
// hence, it cannot be instantiated
// however, we can use the explicit instantiations
Point<float,3>().set<0>(0);
Point<float,3>().set<1>(0);
Point<float,3>().set<2>(0);
// does not compile (linker error):
//Point<int,3>().set<0>(0);
//Point<float,4>().set<0>(0);
//Point<float,3>().set<4>(0);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.