Link to home
Start Free TrialLog in
Avatar of chcw
chcwFlag for Hong Kong

asked on

Cannot invoke a template member function?

I define a template function in a class called CTestClass, as follows:

class CTestClass
{
public:
CTestClass();
virtual ~CTestClass();

public:
template<class T> void f() {
...
do something
...
};
};

Then I need to invoke the template function f, as follows:

CTestClass TestClass;

TestClass.f<int>();
^^^^^^^^^^^^

But the above statement always get a compile error:

error C2062: type 'int' unexpected.

However, if I define the template function f as a global function intead in a class, like this,

template<class T> void f() {
...
do something
...
};

then the compile will be correct.

What's wrong with this?
Avatar of AlexFM
AlexFM

class CTestClass
{
public:
    CTestClass(){};
    virtual ~CTestClass(){};

public:
    template<class T> void f()
    {
    };
};


int _tmain(int argc, _TCHAR* argv[])
{
    CTestClass TestClass;
    TestClass.f<int>();

    return 0;
}

This is compiled in VC++ 8.0. What version do you use?
Avatar of chcw

ASKER

I'm using Visual C++ 6.0
ASKER CERTIFIED SOLUTION
Avatar of AlexFM
AlexFM

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi there,

I have had trouble with explicite instantiation too (VC6++).
And my workaround was a dummy argument to the template function to specifiy the template type

class A
{
  public:
   A() {;}
   template <class T> void Func(T* pT)
   {
   }
};

//** then this implicite instant. will work.

  A        a;
  double d
  a.Func(&d);

Cheers,
Sebastian
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
AlexFM noted correctly.
>Your code is correct according to C++ standard, but VC++ 6.0 developed in 1998 doesn't support it.

I explained that
> explicit specialization for (template) member functions does not work in VC++6, but implicite specialization can be used instead in VC++6.
  (the whole class does not neccessarily have to be templated)

That solves the problem for the Asker.
Either that or switching to VC++8.

Sebastian