繁体   English   中英

模板类中专用功能的声明

[英]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;
}

据我了解,这是其定义的最一般形式。

在主函数中,我创建一个以floatT 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM