0

I don't know why i am not able to instantiate an Object of the class B in a completely specialized function in spite of declaring the function as a friend in the class B.Please help.I don't know if its a silly doubt but I am Learning C++ Templates for the first time. I am getting the following error:

1>c:\users\google drive\learnopencv\learningc\templateexample.cpp(12): error C2065: 'B' : undeclared identifier
1>c:\users\google drive\learnopencv\learningc\templateexample.cpp(12): error C2062: type 'int' unexpected
1>
1>Build FAILED.
1>
1>Time Elapsed 00:00:00.37
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========




#include "stdafx.h"
    using namespace std;
    template<typename V>
    void DoSomething(V v) //Generic Function
    {
        B<char> s;
        s.data=1;
    };
    template<>
    void DoSomething<int>(int cv) //Specialized Function
    {
        B<int> b1l; // not able to instantiate an object of class B
    };
    template<typename T>                  //Template class B
    class B
    {
        int data;
        template<class X1>
        friend void DoSomething<X1>(X1);
    };

    int main(int argc,char *argv[])
    {
        int x=12;
        DoSomething(x);

        return 0;
    }
Anderson neo
  • 195
  • 2
  • 7
  • 17

1 Answers1

2

When you define

template<typename V>
void DoSomething(V v) //Generic Function
{
    B<char> s;
    s.data=1;
};

B isn't defined yet, so you get the error. Nothing some re-ordering can't fix:

using namespace std;
template<typename T>                  //Template class B
class B
{
    int data;
    template<class X1>
    friend void DoSomething(X1);
};
template<typename V>
void DoSomething(V v) //Generic Function
{
    B<char> s;
    s.data=1;
};
template<>
void DoSomething<int>(int cv) //Specialized Function
{
    B<int> b1l; // not able to instantiate an object of class B
};
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • The generic function doesn't have any issue. Specialized function is giving the problem.If I comment the line of code B b1l;.The code works fine! – Anderson neo Sep 10 '12 at 11:18
  • 1
    @vevin1986 that's because you're not using it yet. You can either take the advice of defining everything before usage, or not. Your choice. If you don't, this will come back to haunt you. – Luchian Grigore Sep 10 '12 at 11:20
  • Thank you so much for your Luchain..Its working...I was stuck with it for past 2 hours..Thanks so much... – Anderson neo Sep 10 '12 at 11:24