在完全专用的模板函数中实例化类的对象

Instantiate an Object of a Class in completely specialized template function

本文关键字:实例化 对象 函数 专用      更新时间:2023-10-16

我不知道为什么我不能在一个完全专用的函数中实例化B类的对象,尽管我在B类中声明了该函数为朋友。请帮助。我不知道这是不是一个愚蠢的怀疑,但我是第一次学习C++模板。我得到以下错误:

1>c:usersgoogle drivelearnopencvlearningctemplateexample.cpp(12): error C2065: 'B' : undeclared identifier
1>c:usersgoogle drivelearnopencvlearningctemplateexample.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;
    }

定义时

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

B尚未定义,因此会出现错误。没有什么是一些重新订购无法修复的:

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
};