Home > database >  Static_cast and templated conversion function
Static_cast and templated conversion function

Time:11-27

I have a class that wraps some type and attaches a Dimension. It should be convertible to the underlying type, but only if Dim=0. The conversion operator should not be callable in other cases (so a static_assert in the function would not work for me).

The following code works, if the enable_if-construction is deleted, but not in this form.

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?

CodePudding user response:

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

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

  • Related