![](/img/trans.png)
[英]Is it possible to explicitly instantiate a templated function that returns an unspecified type?
[英]Can't explicitly instantiate templated function into templated class
我不明白為什么下面的代碼不起作用,為什么我不能顯式實例化模板化的函數? 如果我刪除那個<int>我得到一個“沒有匹配的函數調用”
#include <iostream>
using namespace std;
template <typename T>
class Xclass
{
public:
template <typename Y>
void xfunc()
{
cout << "Hello";
}
};
template<typename T2>
class Z
{
public:
void x2()
{
Xclass<T2> obj;
obj.xfunc<int>();
}
};
int main() {
Z<int> obj;
obj.x2();
return 0;
}
錯誤是:
prog.cpp: In member function ‘void Z<T2>::x2()’:
prog.cpp:24:15: error: expected primary-expression before ‘int’
obj.xfunc<int>();
^
prog.cpp:24:15: error: expected ‘;’ before ‘int’
由於obj
的類型是依賴類型,因此必須使用template
關鍵字告訴編譯器它是一個模板:
Xclass<T2> obj;
obj.template xfunc<int>();
看看我在哪里以及為什么要放置“template”和“typename”關鍵字? 有關何時使用template
的詳細說明。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.