相关疑难解决方法(0)

用户定义的转换运算符模板和内置运算符:不匹配运算符

考虑以下MCVE.

#include <type_traits>

struct A {
    template<typename T, typename std::enable_if<std::is_same<T,int>::value,int>::type = 0>
    operator T() const { return static_cast<T>(1); }
};

int main() {
    int x = 1;
    A a;
    return x + a;
}
Run Code Online (Sandbox Code Playgroud)

clang汇编得很好.DEMO

海湾合作委员会失败了:

error: no match for 'operator+' (operand types are 'int' and 'A')
  return x + a;
         ~~^~~
Run Code Online (Sandbox Code Playgroud)

问题:谁是对的?为什么?

c++ language-lawyer c++11

9
推荐指数
1
解决办法
167
查看次数

GCC 中模板化转换运算符中的错误:解决方法?

我想要一个代表具有某种维度的单位的类。这应该表示 1.5m^2 之类的东西。应允许与某种类型进行标量乘法,并且无量纲单位的行为应与基础类型完全相同。这是我的解决方案:

#include <type_traits>

template<typename T, int Dim>
class Unit {
    public:
    explicit Unit(T t): _value(t) {}

    template<int D = Dim, typename std::enable_if_t<D==0, int> = 0>
    operator T() { static_assert(Dim==0, ""); return _value; } //static_assert not necessary, but gives error if template is removed
    T _value;
};

template<typename S, typename T, int Dim>
auto operator*(S s, Unit<T,Dim> unit)
{
    return Unit<T, Dim>(s * unit._value);
}

auto main() -> int
{
    auto i = double{0};

//Scalar test
    auto scalar = …
Run Code Online (Sandbox Code Playgroud)

c++ gcc sfinae implicit-conversion

5
推荐指数
1
解决办法
105
查看次数

标签 统计

c++ ×2

c++11 ×1

gcc ×1

implicit-conversion ×1

language-lawyer ×1

sfinae ×1