c++ - 模板之间的隐式转换

标签 c++ templates implicit-conversion conversion-operator

我不太明白为什么这段代码不能编译。 应该可以像这样调用 dist() :

dist(GenericVec2<T>,GenericVec3<T>)

(无论这多么可怕)。这个想法是 GenericVec3 参数被转换运算符隐式转换为 GenericVec2 。 我在这里找到了这个问题

C++ implicit type conversion with template

,但我不太确定它是否可以应用于我的问题(将转换运算符设置为“friend”无效)。 VS 输出以下错误:

error C2672: 'dist': no matching overloaded function found
error C2784: 'F dist(const GenericVec2<F> &,const GenericVec2<F> &)': could not deduce template argument for 'const GenericVec2<F> &' from 'Vec3'
note: see declaration of 'dist'

这是我的代码:

#include <iostream>

template<typename F> struct GenericVec2
{
    GenericVec2<F>::GenericVec2(F _x = 0, F _y = 0) : x(_x), y(_y) {}

    F x;
    F y;
};
using Vec2 = GenericVec2<float>;

template<typename F> struct GenericVec3
{
    GenericVec3<F>::GenericVec3(F _x = 0, F _y = 0, F _z = 0) : x(_x), y(_y), z(_z) {}

    operator GenericVec2<F>()               { return *reinterpret_cast<GenericVec2<F>*>(&x); }
    operator const GenericVec2<F>() const   { return *reinterpret_cast<const GenericVec2<F>*>(&x); }

    F x;
    F y;
    F z;
};
using Vec3 = GenericVec3<float>;

template<typename F> F dist(const GenericVec2<F>& a, const GenericVec2<F>& b)
{
    return std::hypot(a.x - b.x, a.y - b.y);
}

int main()
{
    Vec2 a{ 2.0f, 3.0f };
    Vec3 b{ 1.0f, 1.0f, 1.0f };
    Vec2 c = b;

    float d = dist(a, Vec2{ b });   // works
    float e = dist(a, b);           // doesn't compile

    std::cin.ignore();

    return 0;
}

提前致谢!

-托马斯

最佳答案

问题是,在

template<typename F> F dist(const GenericVec2<F>& a, const GenericVec2<F>& b)

你不能从 GenericVec2<float> 推导出第二个参数. 由于 friend,一种解决方案是使函数成为非模板:

template<typename F> struct GenericVec2
{
    GenericVec2<F>::GenericVec2(F _x = 0, F _y = 0) : x(_x), y(_y) {}


    friend F dist(const GenericVec2& a, const GenericVec2& b)
    {
        return std::hypot(a.x - b.x, a.y - b.y);
    }

    F x;
    F y;
};

关于c++ - 模板之间的隐式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44282426/

相关文章:

c++ - 为什么下面的代码会出错(关于重载解析)

javascript - 在这种情况下我应该使用 JavaScript 原型(prototype)吗?

c++ - std::map::const_iterator 模板编译错误

c - 看K&R书时signed和unsigned的隐式转换混淆

Scala:使用隐式证据的通用方法无法编译

c++ - 构造函数转换在 C++ 中如何工作?

c++ - 如何定义一个lambda函数来捕获类的 'this'指针?

c++ - 图中的点对点路径

c++ - 使用 Pair 模板实现 List 模板

html - 如何在 GO、Google App Engine 中解析 HTML 模板