C++模板类的申明和定义分离的实现方法

VectorD.h

//
// Created by LiuQiang on 2020/12/31.
//

#ifndef ROBOTICS_MATH_VECTOR3D_H
#define ROBOTICS_MATH_VECTOR3D_H

#include 
#include 

namespace math {
     
    template<typename T = double>
    class Vector3D {
     
    private:
        Eigen::Matrix<T, 3, 1> m_vec;

    public:
        Vector3D();

        Vector3D(T x, T y, T z);

        T &operator[](size_t n);

        const T &operator[](size_t n) const;

        template<typename R> //友元函数需要加这个
        friend std::ostream &operator<<(std::ostream &os, const Vector3D<R> &vec);
    };
}


#endif //ROBOTICS_MATH_VECTOR3D_H

Vector3D.cpp

//
// Created by LiuQiang on 2020/12/31.
//

#include "Vector3D.h"
#include 

namespace math {
     
    template<typename T>
    Vector3D<T>::Vector3D() {
     
        m_vec << 0, 0, 0;
    }

    template<typename T>
    Vector3D<T>::Vector3D(T x, T y, T z) {
     
        m_vec << x, y, z;
    }

    template<typename T>
    T &Vector3D<T>::operator[](size_t n) {
     
        assert(n <= 2);
        return m_vec[n];
    }

    template<typename T>
    const T &Vector3D<T>::operator[](size_t n) const {
     
        assert(n <= 2);
        return m_vec[n];
    }

    template<typename R>
    std::ostream &operator<< (std::ostream &os, const Vector3D<R> &vec) {
     
        return os << "Vector3D {" << vec[0] << ", " << vec[1] << ", " << vec[2] << "}";
    }

    template
    class Vector3D<double>; //模板类需要特化

    template
    class Vector3D<float>; //模板类需要特化

    template std::ostream &operator<<(std::ostream &output, const Vector3D<double> &vec); //重载输出运算符需要特化
    template std::ostream &operator<<(std::ostream &output, const Vector3D<float> &vec); //重载输出运算符需要特化
}

这是我不断试错,摸索出来的一个可行的方案。

你可能感兴趣的:(CPP)