1

以下代码在VC10中可以很好的编译:

#include <vector>
#include <iostream>
#include <math.h>



#define _USE_MATH_DEFINES
#include <math.h>
#include <assert.h>
#include <iostream>
#include <vector>
#include <utility>
#include <functional>
#include <numeric>
#include <algorithm>
#include <limits>


    template <typename T>
    class  Coordinate
    {
    public:
        T x_;  ///< x_coordinate
        T y_;  ///< y_coordinate
        /**
        * Default constructor
        */
        Coordinate():x_(0),y_(0){};
        /**
        * Default deconstructor
        */
        ~Coordinate() {};

        /**
        * distance between two points
        */
        template<typename outputType>
        outputType distance( const Coordinate<T> &obj) const
        {
            outputType dis_x = x_-obj.x_;
            outputType dis_y = y_-obj.y_;
            return static_cast<outputType>(sqrt( (double)(dis_x*dis_x)+(double)(dis_y*dis_y)));
        }
    };




    /**
    * This function is used to calculate the distance between two points
    * @relates Coordinate
    * @param pt1 Point 1
    * @param pt2 Point 2
    * @return the distance
    */
    template<typename BaseType, typename OutputType >
    inline OutputType Distance(const Coordinate<BaseType> &pt1, const Coordinate<BaseType> &pt2)
    {
        OutputType dis;

        dis = pt2.distance<OutputType>(pt1);

        return dis;
    }

    /**
    * This function is used to calculate the distance between one point with
    * an array of data sets.
    */
    template<typename BaseType, typename OutputType>
    void Distance(const std::vector<Coordinate<BaseType> > &pt_array,
        const Coordinate<BaseType> &pt,
        std::vector<OutputType> &dis_array)
    {
        int len = pt_array.size();
        dis_array.resize(len);
        for(int i=0; i<len; i++)
        {
            dis_array[i] = pt.distance<OutputType>(pt_array[i]);
        }
    }


int main()
{


  int a;
  Coordinate<float> pt1;
  Coordinate<float> pt2;

  pt1.x_ = 2;
  pt1.y_ = 3;
  pt2.x_ = 4;
  pt2.y_ = 5;

  a = Distance<float,int>(pt1,pt2);
  std::cout<<a<<std::endl;

return 1;
}

但是,在使用g++ 4.6的ubuntu linux CodeBlocks编译时,出现如下错误:

 In function ‘OutputType Distance(const Coordinate<BaseType>&, const Coordinate<BaseType>&)’:
           error: expected primary-expression before ‘&gt;’ token
 In function ‘void Distance(const std::vector<Coordinate<BaseType> >&, const Coordinate<BaseType>&, std::vector<OutputType>&)’:
  error: expected primary-expression before ‘&gt;’ token

有任何想法吗?非常感谢!

4

1 回答 1

4

由于pt2是模板类型,因此您必须指定调用的函数是模板:

dis = pt2.template distance<OutputType>(pt1);

Visual Studio 可以在没有template关键字的情况下解决这个问题,但这不是标准行为。

于 2013-05-31T08:47:46.020 回答