【问题标题】:Static_cast and templated conversion functionstatic_cast 和模板化转换函数
【发布时间】:2022-01-04 14:09:56
【问题描述】:

我有一个包含某种类型并附加维度的类。它应该可以转换为基础类型,但前提是Dim=0。转换运算符在其他情况下不应被调用(因此函数中的 static_assert 对我不起作用)。

如果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;
}  

这是什么原因,是否有解决方法允许强制转换,但也限制转换?

【问题讨论】:

  • 它应该可以转换为基础类型,但是您正在从double 构造u 并尝试将其转换为int,这不是我猜是“底层类型”。你能澄清一下吗?

标签: c++ type-conversion sfinae


【解决方案1】:

据我了解,您想要:

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

在 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

【讨论】:

  • 这可能会因转换为T 而过载,以获得最佳默认选择,对吧?
  • 不知道你的意思,在上面的例子中,operator int()是创建的,而不是static_cast&lt;int&gt;(static_cast&lt;double&gt;(u))...
猜你喜欢
  • 2020-02-19
  • 1970-01-01
  • 2012-06-16
  • 2022-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-19
相关资源
最近更新 更多