![](/img/trans.png)
[英]Expression Templates: error C2784 'could not deduce template argument'
[英]Trouble with templates. Error : Cannot deduce template argument for type 'T'
試圖將模板實現到readInSearchCriterion方法中以處理double / string / Date。 無法推斷出模板參數“ T”為當前狀態。
在UserInterface.cpp中
宣言:
template <typename T> T readInSearchCriterion() const;
定義:
template<typename T>
T UserInterface::readInSearchCriterion() const
{
T val;
cout << "Enter search value: ";
cin >> val;
return val;
}
在CashPoint.cpp中,雙(金額)存儲搜索條件(例如50)
amount = theUI_.readInSearchCriterion();
當您編寫模板函數時:
template<class T> void foo( T arg );
您假設將其稱為指定類型:
foo<int>( 1 );
如果編譯器可以計算或推導類型,則可以省略完整形式並使用簡短形式:
foo( 1 ); // same as before, <int> deduced from arg type, which is int(1) in this case
編譯器不允許根據語言規則推斷出返回類型(為什么不在此問題范圍之內),因此,如果僅在返回中使用模板類型,請使用完整格式:
template<class T> T foo();
int i = foo<int>(); // ok
int i = foo(); // error
這與鏈接器未解析的符號無關,這很可能意味着您將實現放在cpp文件中,但是在使用它的任何地方都必須可見(或者對於它要使用的所有類型,都必須使用顯式實例化)。 最簡單的解決方案-將實現放入標頭中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.