简体   繁体   English

C ++ Setup拥有模板类/结构的强制转换规则

[英]C++ Setup own cast rules for template classes/structures

is it possible to implement your own cast rules and to make the compiler give a warning about it rather than an error? 是否可以实现自己的强制转换规则并使编译器发出警告而不是错误?

I'm currently working with SFML (doesn't really matter if you don't know it) and it has a simple Vector2 structure like this: 我目前正在使用SFML(如果你不知道它并不重要)并且它有一个简单的Vector2结构,如下所示:

template <typename T>
struct Vector2 {
    Vector2<T>(T,T);
    T x,y;
}

Now I'm using this quite often and would like to setup a custom cast rule for this structure, since I can't modify the source code. 现在我经常使用它,并希望为此结构设置自定义强制转换规则,因为我无法修改源代码。 I currently have a function that needs a Vector2<int> , but a function I use returns a Vector2<unsigned int> and the compiler doesn't seem to be able to cast the one into the other which is a bit weird. 我目前有一个需要Vector2<int>的函数,但是我使用的函数返回一个Vector2<unsigned int> ,并且编译器似乎无法将一个函数转换为Vector2<unsigned int>的函数。

I know I can use the casts (and static_cast works), but it seems a bit too elaborate for aa simple conversion like this, and a bit stupid that I can't test my program because of this. 我知道我可以使用强制转换(和static_cast工作),但对于像这样的简单转换似乎有点过于复杂,有点愚蠢,因为这个我无法测试我的程序。 So what I'm probably searching for are compiler commands that can setup such cast rules. 所以我可能正在寻找的是可以设置这样的强制转换规则的编译器命令。

There are two ways to do this (both ways require you to modify the definition of Vector2 ). 有两种方法可以执行此操作(两种方法都需要您修改Vector2的定义)。 You can add a non-explicit constructor that performs the conversion: 您可以添加执行转换的非显式构造函数:

template <typename T>
struct Vector2 {
    template<typename U>
    Vector2(Vector2<U> const& u) : x(u.x), y(u.y){}
    Vector2(T x,T y) : x(x), y(y) {}
    T x,y;
};

or you can add a non-explicit type-cast operator: 或者您可以添加非显式类型转换运算符:

template <typename T>
struct Vector2 {
    template<typename U>
    operator Vector2<U>(){
        return Vector2<U>(x,y);
    }
    Vector2(T x,T y) : x(x), y(y) {}
    T x,y;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM