gpt4 book ai didi

c++ - 如何创建将 Class 转换为 Class 的函数,其中 T 和 U 是任意数字类型?

转载 作者:行者123 更新时间:2023-11-28 00:11:32 25 4
gpt4 key购买 nike

我正在使用 SFML,我想做如下事情:

sf::Texture myTexture;
myTexture.loadFromFile("texture.png");

sf::Sprite mySprite(myTexture);
mySprite.setOrigin(myTexture.getSize() / 2.f); // <~-- error

问题是 sf::Texture::getSize()返回 sf::Vector2< <强> unsigned > , 而 sf::Transformable::setOrigin()期待 sf::Vector2< <强> float > ,并且它们不能相互转换。

我想创建一个函数来接受任何 sf::Vector2<T>并返回一个等价的 sf::Vector<U> , 其中TU都是任意数字类型,所以我可以将最后一行代码重写为:

// converting from 'unsigned' to 'float'
mySprite.setOrigin(toVector2<unsigned, float>(myTexture.getSize()) / 2.f);

我目前拥有的是以下内容,但它不起作用。

// Util.h
namespace smi
{
template <typename FROM, typename TO>
sf::Vector2<TO> toVector2(const sf::Vector2<FROM> &other)
{
return sf::Vector2<TO>(
static_cast<TO>(other.x),
static_cast<TO>(other.y));
}
}

// then ...
mySprite.setOrigin(toVector2<unsigned, float>(myTexture.getSize()) / 2.f);
// ^ no instance of function template "toVector2" matches the argument list

这是显示错误的图像:

Error message: no instance of function template "toVector2" matches the argument list

我怎样才能实现这种通用转换?

最佳答案

通常,您不能对任意类型执行此操作。类模板的两个不同特化之间不一定有任何关系,也没有从一个转换到另一个的通用方法。

对于特定情况,您通常可以执行以下操作:

template <typename To, typename From>
Thing<To> convert(const Thing<From>& from)
{
return Thing<To>( /* internal value(s) of from */ );
}

即从源对象中保存的值构造一个新对象。但要做到这一点,您需要了解该类型的 API,以便您可以获取值并调用适当的构造函数,例如

template <typename To, typename From>
std::complex<To> convert_complex(const std::complex<From>& from)
{
return std::complex<To>( from.real(), from.imag() );
}

或:

template <typename To, typename From>
std::vector<To> convert_vector(const std::vector<From>& from)
{
return std::vector<To>( from.begin(), from.end() );
}

或:

template <typename To, typename From>
std::shared_ptr<To> convert_shared_ptr(const std::shared_ptr<From>& from)
{
return std::dynamic_pointer_cast<To>(from);
}

但是没有办法完全通用地做到这一点,因为每种类型都有不同的 API 来获取其内部值(如果可能的话)和构造新对象。

你的 toVector2函数看起来应该可以工作,因为它正是这样做的。正如皮特指出的那样,该错误表明您尚未定义 toVector2功能如您的问题所示:您以相反的方式放置参数!

注意您可以重新排序模板参数,以便您可以使用模板参数推导来简化您的转换函数:

template <typename To, typename From>
sf::Vector2<To> toVector2(const sf::Vector2<From>& other)
{
return ...
}

现在你可以调用toVector2<float>(myTexture.getSize())From参数将被推断为 unsigned .

因为这似乎是您定义实际函数的方式,只需将代码更改为 toVector2<float>(myTexture.getSize())它应该有效。

关于c++ - 如何创建将 Class<T> 转换为 Class<U> 的函数,其中 T 和 U 是任意数字类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32828730/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com