0
struct MyStruct
{
    MyStruct() {}
};
struct MySndStruct
{
    MySndStruct() {}
};

template <typename T> 
T Func(const T& t = T()) 
{ 
    T ret;
    return ret;
}

template <> 
MyStruct Func<MyStruct>(const MyStruct& ms)
{
    MyStruct ret;
    return ret;
}
int main()
{
    Func<MySndStruct>();
    Func<MySndStruct>(); // Works

    Func<MyStruct>();
    Func<MyStruct>(); // Fails
    Func<MyStruct>(MyStruct()); // Works fine
    return 0;
}

The second invocation of the MyStruct specialization for Func fails with the following error in Visual C++ 2010

error C2440: 'default argument' : cannot convert from 'MyStruct *' to 'MyStruct &

If I pass by value instead of by reference (MyStruct Func<MyStruct>(MyStruct ms)) the error becomes

fatal error C1001: An internal error has occurred in the compiler.

Is this a bug in Microsoft's c++ compiler or is default parameters not supported with template specializations?

If anyone can explain to me whats happening here, for instance, why does the compiler assume a pointer is passed in when it's IMO clearly not? And why does the first invocation work? I assume it has something to do with instantiating the template, but I'd like to know more precisely.

EDIT: Updated parameters to be const to highlight that this does not make a difference on Visual C++ 2010.

hanDerPeder
  • 397
  • 2
  • 12
  • 1
    First error `(T& t = T())`. You cannot bind temporary to reference by standard. Code compiles fine on gcc after fix this: http://liveworkspace.org/code/1b8fecded33ebc25a6eb8519c6a083ea – ForEveR Sep 06 '12 at 11:57
  • Thanks ForEverR. The fix you suggested does not work with Visual C++ 2010. Would this imply it's a bug in the compiler? – hanDerPeder Sep 06 '12 at 14:27
  • Don't works for me in MSVC 2010, but works well in MSVC 2012 RC. – ForEveR Sep 06 '12 at 14:35
  • Okay, thanks for the reply ForEveR. Good enough for me. – hanDerPeder Sep 06 '12 at 14:37

1 Answers1

1

replace T Func(T& t = T()) with T Func(const T& = T()) and it shall compile fine.

Walter
  • 44,150
  • 20
  • 113
  • 196
  • MSVC is cunning. http://stackoverflow.com/questions/11508607/rvalue-to-lvalue-conversion-visual-studio – ForEveR Sep 06 '12 at 12:41
  • Adding const to the parameter gives exactly the same error. Perhaps I should have mentioned that in the original question, but it's irrelevant so I left it out. – hanDerPeder Sep 06 '12 at 14:25
  • sorry, not for me (using gcc 4.7.0). So I cannot help here ... But you should have asked the question with the `const`. – Walter Sep 07 '12 at 18:12