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

标签 c++ visual-studio-2010 templates friend-function

我不知道为什么我无法在一个完全专门的函数中实例化 B 类的对象,尽管在 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
};

关于c++ - 在完全专用的模板函数中实例化一个类的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12350466/

相关文章:

c++ - 如何从 ruby​​ 中调用 C++ 函数

c++ - 有没有一种方法可以一次/多次处理一个数组的所有元素?

visual-studio-2010 - VS 2010 - 导入导出设置

c++ - 查找派生模板类型

c++ - 调用了错误的模板函数

c++ - 避免错误的用户输入(当要求的是整数时为字符串)

c++ - 对象生存期内 `this`指针的值是否恒定?

asp.net - ASP.NET 中的成员资格实现

visual-studio-2010 - 调试后删除项目引用

c++ - 具有多个参数的模板化类特化,其中一个模板参数就是模板本身