Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/147.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在C+中使用模板+;_C++_Templates_Generics - Fatal编程技术网

C++ 在C+中使用模板+;

C++ 在C+中使用模板+;,c++,templates,generics,C++,Templates,Generics,我正在尝试在类中执行泛型方法,现在,我有如下内容: #include "stdafx.h" #include <sstream> #include <iostream> #include <conio.h> using namespace std; class Test { public: template<class T> T returnVal(T value); } template<class T> T

我正在尝试在类中执行泛型方法,现在,我有如下内容:

#include "stdafx.h"
#include <sstream>
#include <iostream>
#include <conio.h>

using namespace std;


class Test
{
public:
    template<class T>
    T returnVal(T value);
}

template<class T>
T Test::returnVal(T value)
{
    return value;
}


int main()
{
    string reference = "stringVal";
    Test ref;
    cout << ref.returnVal<string>(reference);
    getch();
    return 0;
}
#包括“stdafx.h”
#包括
#包括
#包括
使用名称空间std;
课堂测试
{
公众:
模板
T返回值(T值);
}
模板
T测试::返回值(T值)
{
返回值;
}
int main()
{
string reference=“stringVal”;
试验参考;

cout''模板以下编译和运行符合预期:

#include <iostream>

using namespace std;

struct Test
{
    template<class T>
    T returnVal(T value);
};

template<class T>
T Test::returnVal(T value)
{
    return value;
};


int main()
{
    string reference = "stringVal";
    Test ref;
    cout << ref.returnVal<string>(reference);
    return 0;
}
#包括
使用名称空间std;
结构测试
{
模板
T返回值(T值);
};
模板
T测试::返回值(T值)
{
返回值;
};
int main()
{
string reference=“stringVal”;
试验参考;

难道你漏掉了一个分号

只需在类定义之后添加一个

class Test
{
 ...
};
 ^
 |
 +---- HERE

您的代码太不完整(缺少include、类定义后缺少分号等)如果没有其他错误,
returnVal
private
,您不能从类外调用它。另外,也不要忘记将函数
设置为public
。如果显式使用泛型函数,它能工作吗?ref.returnVal(参考);@Deniseskimore:不应该,因为
returnVal
的定义是错误的(应该是
template t Test::returnVal(t value)
或类似的)。我重复一遍:在类定义后缺少分号。