Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiler error when using template specialization under Visual C++

I have the following cpp code:

#include <iostream>
#include <limits>

// C2589 when compiling with specialization, fine when compiling without
template<typename T>
void foo(T value = std::numeric_limits<T>::infinity() )
{
}

// this specialization causes compiler error C2589 above
template<>
void foo<float>( float value )
{
}

int main()
{
    foo<float>();
    return 0;
}

When I try to compile this using Visual Studio 2013, I get the following error:

..\check2\main.cpp(5) : error C2589: '::' : illegal token on right side of '::'
..\check2\main.cpp(5) : error C2059: syntax error : '::'

The program compiles fine if I don't include the specialization foo<float>. The code also compiles fine including the specialization under gcc 4.8.4, which indicates some problem with the Visual C++ compiler.

Is the code correct and should it compile? Is there a workaround for Visual C++?

like image 914
dkoerner Avatar asked Feb 23 '16 16:02

dkoerner


1 Answers

By omitting the parameter when calling foo<float>(); you are placing compiler into a conundrum. Compiler simultaneously concludes that specialized function is the right one to choose because you explicitly say <float>, and is not the one because there is no parameter. Compiler then reaches for the general version, but it can't because there is a specialized one. Even HAL9000 couldn't figure out that one, unless it's built with gcc. VC++ incorrectly handles the situation. Probably a bug, and not "by design".

Workaround for Visual C++ is to use overloading:

template<typename T>
void foo(T value)
{
}

template<typename T>
void foo()
{
    foo(std::numeric_limits<T>::infinity());
}

And call it as usual foo<float>();

like image 154
Dialecticus Avatar answered Nov 13 '22 13:11

Dialecticus