Jump to content
  • Advertisement
Sign in to follow this  
Sc4Freak

Why doesn't this work?

This topic is 3473 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
Advertisement
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
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
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!