【问题标题】:What is wrong with my template specialization?我的模板专业化有什么问题?
【发布时间】:2021-03-25 11:34:48
【问题描述】:

我想提供几个转换函数,将我的自定义结构转换为其他类型。这些函数应该被返回返回类型重载。我已经尝试过如下模板专业化。

我收到此编译器错误消息:

class cv::Rect __cdecl convert<class cv::Rect >(struct MyRect const &)" already defined in CallerCode.obj.

我的代码有什么问题?

MyRect.h

struct MyRect
{
    float lux, luy, rlx, rly;

    float width() const;
    float height() const;
};

库代码

class cv::Rect;
struct OtherRect;

Conversion.h

template<typename T> T convert(const MyRect& r);

template<> cv::Rect convert<cv::Rect>(const MyRect& r)
{
    return cv::Rect(r.lux, r.luy, r.width(), r.height());
}

template<> OtherRect convert<OtherRect>(const MyRect& r)
{
    return OtherRect(r.lux, r.luy, r.rlx, r.rly);
}

调用代码

MyRect r{ 0.f, 0.f, 0.f, 0.f };
const cv::Rect cr = convert<cv::Rect>(r);

【问题讨论】:

  • 什么是OtherRect?还有为什么是float 而不是double
  • @tadman float 因为 openCV 我认为...
  • @JHBonarius 好点。以为这只是不必要的小气。
  • @tadman OtherRect 我为了演示而编造了一些内容,以展示我想如何使用不同的类型。 float vs double 与问题无关(也可以是int 或任何类型,问题保持不变)。
  • 我只是在问,因为这是否是可以解释很多的同一事物的别名。如果它是一种完全不同的类型,值得这么说。我提到了float,因为后来人们常常开始抱怨缺乏精确度。

标签: c++ templates template-specialization


【解决方案1】:

完全特化不再是模板函数,因此不再隐含inline

你必须添加inline

template<> inline cv::Rect convert<cv::Rect>(const MyRect& r)
{
    return cv::Rect(r.lux, r.luy, r.width(), r.height());
}

或在头文件中拆分声明和cpp文件中的定义

// Declaration: in header
template<> cv::Rect convert<cv::Rect>(const MyRect&);
// Definition: in cpp file
template<> cv::Rect convert<cv::Rect>(const MyRect& r)
{
    return cv::Rect(r.lux, r.luy, r.width(), r.height());
}

【讨论】:

  • 但是我的语法正确吗?那么将专门的函数移到 .cpp 文件中就足够了吗?
  • @Sparkofska:您需要在标题中的 声明
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多