Search code examples
c++visual-studiovisual-studio-2017template-specializationfunction-templates

Specializing a Template With a Return Type Derived by decltype in Visual Studio


Given the following code:

template<typename ValueType>
decltype(ValueType{} == ValueType{}) Compare(const ValueType& value, const ValueType& expected)
{
    return value == expected;
}

template<>
decltype(float{} == float{}) Compare<float>(const float& value, const float& expected)
{
    return std::abs(value - expected) < 1e-4F;
}

I would expect the call Compare(13.0F, 42.0F) to correctly call the specialization, which it does on gcc. But it fails to on . I get the error:

error C2912: explicit specialization bool Compare<float>(const float &,const float &) is not a specialization of a function template

Is there something I can do to help guide ?


Solution

  • Purely to appease VC++, you may extract the return type as another template argument.

    template<typename ValueType, typename RetType = decltype(ValueType{} == ValueType{})>
    RetType Compare(const ValueType& value, const ValueType& expected)
    {
        return value == expected;
    }
    
    template<>
    decltype(float{} == float{}) Compare<float>(const float& value, const float& expected)
    {
        return std::abs(value - expected) < 1e-4F;
    }
    

    That makes VC++ accept the code.