繁体   English   中英

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

[英]Instantiate an Object of a Class in completely specialized template function

我不知道为什么我无法在一个完全专业化的函数中实例化B类的Object,尽管在B类中将该函数声明为朋友。请帮助。我不知道它是否是一个愚蠢的怀疑但我是第一次学习C ++模板。 我收到以下错误:

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

当你定义

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM