简体   繁体   English

static_cast 和模板化转换 function

[英]Static_cast and templated conversion function

I have a class that wraps some type and attaches a Dimension.我有一个 class 包装某种类型并附加一个维度。 It should be convertible to the underlying type, but only if Dim=0 .它应该可以转换为基础类型,但前提是Dim=0 The conversion operator should not be callable in other cases (so a static_assert in the function would not work for me).在其他情况下,转换运算符不应该是可调用的(因此 function 中的static_assert对我不起作用)。

The following code works, if the enable_if -construction is deleted, but not in this form.如果enable_if -construction 被删除,则以下代码有效,但不是这种形式。

template<class T, int Dim>
class Unit {
    public:
    explicit Unit(T const& value): _value(value) {}

    template<int D = Dim, typename = typename std::enable_if<D == 0>::type>
    operator T() { return _value; }
    private:
    T _value;
};

auto main() -> int
{
    auto a = double{0};
    auto u = Unit<double, 0>{a};
    auto i = static_cast<int>(u);    
    return i;
}  

What is the reason for this and is there a work around to allow the cast, but also restrict the conversion?这是什么原因,是否有解决方法来允许演员,但也限制转换?

As I understand, you want:据我了解,您想要:

template <class T, int Dim>
class Unit {
public:
    explicit Unit(T const& value): _value(value) {}

    template <typename U, int D = Dim,
              std::enable_if_t<D == 0 && std::is_convertible_v<T, U>, int> = 0>
    operator U() { return _value; }
private:
    T _value;
};

Demo演示

And in C++20, look nicer而在 C++20 中,看起来更好

template<class T, int Dim>
class Unit {
    public:
    explicit Unit(T const& value): _value(value) {}

    template <typename U>
    requires(Dim == 0 && std::is_convertible_v<T, U>)
    operator U() const { return _value; }
private:
    T _value;
};

Demo演示

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

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