Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function overload resolution trouble

Tags:

c++

Over the weekend, I had specific problem with function overload resolution that I can't seem to solve. The code below is a distillation of the problem:

#include <iostream>
using namespace std;

template<typename T>
void f(const T& t)
{
    cout << "In template function." << endl;
}

class C
{
public:
    void f() { cout << "In class function." << endl; }
    void g() { int i=0; f(i); }
    void h() { int i=0; f<int>(i); }
    void i() { extern void f(int); int i=0; f(i); }
};

int main()
{
    cout << "Test" << endl;
    C c;
    c.i();
    return 0;
}

1) C::g won't compile because the compiler won't try the template. It just complains that there is no C::f to match.

2) C::h won't compile for no reason that is obvious to me. The message is "expected primary-expression before 'int'"

3) C::i will compile, but (after commenting out g and h) it won't link to anything. I think I understand this: the extern is forcing the linker to look into another compilation unit, but any template definition would be in this compilation unit.

I would appreciate any clarification on the reasons for 1 and 2. Also, ultimately, can someone suggest a way to get this to work that doesn't involve creating another compilation unit?

like image 506
John Avatar asked Oct 03 '11 14:10

John


2 Answers

Likely it is finding C::f instead of global f. Use ::f<int>(i).

like image 163
Daniel A. White Avatar answered Oct 12 '22 08:10

Daniel A. White


Look here: http://ideone.com/zs9Ar

Output:

Test
In template function.

#include <iostream>
using namespace std;

template<typename T>
void f(const T& t)
{
    cout << "In template function." << endl;
}

class C
{
public:
    void f() { cout << "In class function." << endl; }
    void g() { using ::f; int i=0; f(i); }
};

int main()
{
    cout << "Test" << endl;
    C c;
    c.g();
    return 0;
}
like image 42
sehe Avatar answered Oct 12 '22 08:10

sehe