在科学编程的单元管理环境中,我正在管理以下课程:
template <class UnitName>
class Quantity
{
double value;
public:
Quantity(double val = 0) : value(val) {}
Quantity(const Quantity &) {}
Quantity & operator = (const Quantity &) { return *this; }
double get_value() const noexcept { return value; }
operator double() const noexcept { return value; }
template <class SrcUnit>
Quantity(const Quantity<SrcUnit> &)
{
// here the conversion is done
}
template <class SrcUnit>
Quantity & operator = (const Quantity<SrcUnit> &)
{
// here the conversion is done
return *this;
}
template <class TgtUnit> operator TgtUnit() const
{
TgtUnit ret;
// here the conversion is done
return ret;
}
template <class U, class Ur>
Quantity<Ur> operator / (const Quantity<U> & rhs) const
{
return Quantity<Ur>(value / rhs.value);
}
};
Run Code Online (Sandbox Code Playgroud)
虽然课程要复杂得多,但我认为我提供了足够的信息来描述我的问题:
现在考虑以下代码段:
struct km_h {};
struct Km {};
struct Hour {};
Quantity<km_h> compute_speed(const Quantity<Km> & dist,
const Quantity<Hour> & time)
{
Quantity<km_h> v = dist/time;
return v;
}
Run Code Online (Sandbox Code Playgroud)
此代码被gnu c++编译器接受,运行良好./调用最后一个模板运算符.
但它被clang++编译器(v 3.8.1)拒绝,并带有以下消息:
test-simple.cc:53:26: error: use of overloaded operator '/' is ambiguous (with operand
types 'const Quantity<Km>' and 'const Quantity<Hour>')
Quantity<km_h> v = dist/time;
~~~~^~~~~
test-simple.cc:53:26: note: built-in candidate operator/(__int128, unsigned long long)
test-simple.cc:53:26: note: built-in candidate operator/(unsigned long, long double)
Run Code Online (Sandbox Code Playgroud)
所以我的问题是:为什么clang++拒绝呢?是一个有效的代码?还是gnu c++应该拒绝呢?
在代码有效的情况下,如何修改它以clang++接受它?
我相信,铛是有权拒收你的代码†,但GCC实际上并没有做你想要的(什么都dist和time隐式转换为double‡和gcc认为内置的operator/(double, double)是最好的可行的候选人).问题是,你写道:
template <class U, class Ur>
Quantity<Ur> operator / (const Quantity<U> & rhs) const
Run Code Online (Sandbox Code Playgroud)
什么是Ur?这是一个非推断的上下文 - 因此尝试简单地调用此运算符dist / time是一个演绎失败.你的候选人从未被考虑过.为了实际使用它,你必须明确提供Ur如下:
dist.operator/<Hour, km_h>(time); // explicitly providing Ur == km_h
Run Code Online (Sandbox Code Playgroud)
由于这很糟糕,你不能Ur被推断为模板参数 - 你必须自己提供它作为两个单元的一些元函数:
template <class U>
Quantity<some_mf_t<UnitName, U>> operator/(Quantity<U> const& ) const;
Run Code Online (Sandbox Code Playgroud)
与some_mf_t将被定义.
†你有两个operator double()和template <class T> operator T(),这意味着所有内置operator/的同样可行的候选人(他们都是非模板,完全匹配).
‡有operator double()那种失败的写作类型安全单位的目的,不是吗?
| 归档时间: |
|
| 查看次数: |
74 次 |
| 最近记录: |