XCode在C++模板中出现错误

XCode gives an error with C++ templates

本文关键字:错误 C++ XCode      更新时间:2023-10-16

当我使用在VS2010中工作的自定义模板时,我会收到一个错误。这显然是因为系统不同,但我如何让XCode读取模板?这是模板文件:

#ifndef TEMPLATE_H_INCLUDED
#define TEMPLATE_H_INCLUDED
#include <algorithm>
#include <math.h>
#include <vector>
#include <cmath>        // std::abs
#include <float.h>
using namespace std;
namespace Geometry
{
    #if _MSC_VER // this is defined when compiling with Visual Studio
        #define M_PI 3.14159265358979f
    #endif
        #define Deg2Rad(deg)  ((deg) * M_PI / 180)
        #define Rad2Deg(rad)  ((rad) * 180 / M_PI)
        template <typename T> int sgn(T val)
        { return (T(0) < val) - (val < T(0)); }
        template <typename T> bool isnan (T value)
        { return value != value; }
        template <typename T> T Clamp(const T& value, const T& low, const T& high)
        {
          return value < low ? low : (value > high ? high : value);
        }
        template <typename T> T Clamp01(const T& value)
        {
          return value < 0 ? 0 : (value > 1 ? 1 : value);
        }
        /// Return the real part of the square root of x.
        inline float fsqrtf (float x)
        { return x > 0.0f ? std::sqrt (x) : 0.0f; }
};

我对这个标题所做的非常简单。我只是简单地包括标题并开始使用模板。它们在VS2010中工作,但在XCode中不工作,所以我如何解决这个问题?我还在cpp文件的开头使用名称空间Geometry。

这是错误消息:

 No matching function for call to 'Clamp'

根据JBL的要求,以下是代码:

#include "templates.h"
using namespace Geometry;
class Curve
{
    public:
        GetClampedValue(float value);
};
#include "myclass.h"
void MyClass::GetClampedValue(float value)
{
    return Clamp(value,-1,1);// Error Here
}

它就在那里。您发布的代码无法按当前状态编译。

事实上,模板化函数的签名是T(const T&, const T&, const T&),这意味着三个参数必须共享相同的类型。,但是你通过了一个float和两个int。Clang会给你一个很好的错误信息:

忽略候选模板:推导出参数"T"("float"与"int")的冲突类型

要么使用共享相同类型的参数,要么更改模板参数,使其可以接受不同类型,即

template<typename T, typename U, typename V>
T (const T&, const U&, const V&)
{...}

如果您想强制类型具有某些属性(例如std::is_arithmetic),您甚至可以使用类型特征。