Sign in to follow this  
Sc4Freak

Why doesn't this work?

Recommended Posts

Sc4Freak    643
I have a feeling that MSVC is being a little more forgiving than GCC with regards to the following snippet of code:
#include <algorithm>
#include <iostream>

template<typename TFunc>
void DoSomething(TFunc Func)
{
    std::cout << Func(1, 2);
}

int main()
{
    DoSomething(std::max<int>);
    return 0;
}

Compiles and runs just fine in MSVC9, correctly printing "2". When compiling under GCC, I get:
error: no matching function for call to 'DoSomething(<unknown type>)'
What's wrong?

Share this post


Link to post
Share on other sites
Adam_42    3629
Here's one workaround. The problem must have something to do with the definition of std::max - maybe the predicate is causing it?


#include <algorithm>
#include <iostream>

template<typename TFunc>
void DoSomething(TFunc Func)
{
std::cout << Func(1, 2);
}

template<typename T> T max(T x, T y)
{
return x > y ? x : y;
}

int main()
{
DoSomething(max<int>);
return 0;
}

Share this post


Link to post
Share on other sites
visitor    643
This seems to be the eternal damnation of overloaded functions. There are two versions of std::max (second taking a comparison function in addition), and GCC can't tell from what you have which of the overloads you meant. (Don't know why VC++ is able to do that - it is more relaxed about such matter sometimes.)

One workaround that I know of, is to declare a function pointer (or static_cast to function pointer) where the type of that indicates without ambiguity which overload you meant. Unfortunately this looks quite ugly:


#include <algorithm>
#include <iostream>

template<typename TFunc>
void DoSomething(TFunc Func)
{
std::cout << Func(1, 2);
}

int main()
{
const int& (*pmax)(const int&, const int&) = std::max<int>;
DoSomething(pmax);

//or specify the template parameter
DoSomething<const int&(const int&, const int&)>(&std::max<int>);
return 0;
}

Share this post


Link to post
Share on other sites
DevFred    840
Quote:
Original post by Nikko_Bertoa
Is GCC a C++ compiler???

No, GCC is not a compiler at all. It stands for "GNU Compiler Collection", and g++ is one of those compilers (gcc being another one).

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this