考虑以下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)
问题:谁是对的?为什么?
我想要一个代表具有某种维度的单位的类。这应该表示 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)