Question

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;
    }
Was it helpful?

Solution

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
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top