Visual Studio 2013中可能存在ADL错误

时间:2015-05-13 08:57:53

标签: c++ gcc visual-studio-2013 argument-dependent-lookup

以下简化代码无法在VS2013下编译:

#include <cmath>
namespace mine
{
    template <typename A>
    struct Base
    {
        double value() const { return static_cast<const A&>(*this).value(); }
    };

    struct Derived : Base < Derived >
    {
        Derived(double x) : m_val(x) {}
        double value() const { return m_val; }
        double m_val;
    };

    template <typename A>
    bool isnan(const Base<A>& x) { return ::isnan(x.value()); }

    struct ItWorks
    {
        double value() const { return 3.14; }
    };
    bool isnan(ItWorks t) { return ::isnan(t.value()); }
}

int main()
{
    mine::Derived d(2.0);
    bool b = isnan(d); // this one fails in VS2013

    mine::ItWorks t;
    bool bb = isnan(t); // this one works

    return 0;
}

错误是:

c:\program files (x86)\microsoft visual studio 12.0\vc\include\math.h(425): error C2665: 'fpclassify' : none of the 3 overloads could convert all the argument types
could be 'int fpclassify(long double)'
or       'int fpclassify(double)'
or       'int fpclassify(float)'
while trying to match the argument list '(mine::Derived)'

我期待ADL在mine::isnan()上调用时会调用mine::Derived,但出于某种原因,VS2013正试图从全局命名空间调用isnan()模板函数。

当然,如果我直接调用mine::isnan()一切正常,但这并不能解决我的问题,因为我需要在模板化的上下文中调用isnan(),我可能会得到{{1} }或从double派生的任何类。

它必须与模板推导有一些互动,因为一切都按预期的方式运行mine::CRTP:一个简单的结构使用CRTP。

但是,gcc 5.1.0和clang 3.5.1都同意我并正确编译代码。这看起来像VS2013的错误...

有什么想法吗? 谢谢!

1 个答案:

答案 0 :(得分:2)

这似乎不是我所看到的错误。

template<class _Ty> inline __nothrow bool isnan(_Ty _X)

template<typename A> bool isnan(const Base<A>& x)

这些功能将分别解析为

bool isnan(Derived _X)

bool isnan(const Base<Derived>& x)

因此,当isnan被赋予Derived类型时,它将匹配显式使用Derived的函数定义。并且发生错误是因为fpclassify无法处理Derived。

不要试图覆盖具有模板变量类型的isnan,而是覆盖fpclassify函数。

template <typename A>
int fpclassify(const Base<A>& x)
{
    return ::fpclassify(x.value());
}

然后您的实施将有效。

从评论更新

isnan可能位于全局命名空间(来自math.h),而不仅仅是导致冲突的std(cmath)。 - Source