C ++类型转换重载

时间:2016-01-01 11:48:04

标签: c++ generics casting typecast-operator

假设我有一个这样的课程:

template<class T>
class Vector2 {
public:
    Vector2(const T a, const T b) : x(a), x(b) {}
    T x;
    T y;
}

我希望能够做到这样的事情:

const Vector2<double> d(31.4, 48.2);  // note the const!!!

Vector2<int> i = static_cast<Vector2<int>>(d);

// i.x == 31
// i.y == 48

我尝试重载一个泛型运算符,但在尝试从const值转换时似乎破坏了。帮助

2 个答案:

答案 0 :(得分:3)

提供另一个构建函数,该构造函数采用另一个模板参数U

template<class T>
class Vector2 {
public:
    template <class U>
    Vector2(const Vector2<U> & other) : x(other.x), y(other.y){}

    // other code ommited
};

毕竟,您正在尝试使用Vector2<T>::Vector2(const Vector2<U> &)U = doubleT = int

请注意,这与您的原始矢量const无关。相反,您正在尝试构建类型为Vector2<int>的值,其值为另一种类型Value2<double>。这些是不同的类型,因此您需要提供构造函数。

答案 1 :(得分:1)

一种可能性就是编写一个能够做你想做的演员:

public class DenyAttribute : AuthorizeAttribute
{

    protected override bool AuthorizeCore(HttpContextBase httpContext) {
        if (httpContext == null) {
            throw new ArgumentNullException("httpContext");
        }

        IPrincipal user = httpContext.User;
        if (!user.Identity.IsAuthenticated) {
            return false;
        }

        if (Users.Length > 0 && Users.Split(',').Any( u => string.Compare( u.Trim(), user.Identity.Name, StringComparer.OrdinalIgnoreCase))) {
            return false;
        }

        if (Roles.Length > 0 && Roles.Split(',').Any( u => user.IsInRole(u.Trim()))) {
            return false;
        }

        return true;
    }

Zeta答案中显示的另一个构造函数是更优雅的解决方案。