[英]templated method on T inside a templated class on TT : Is that possible/correct
[英]A method returning a templated varible inside a templated class?
這是簡單的代碼:
#include <iostream>
using namespace std;
template <class T>
class A
{
public:
A(T& arg): value(arg) {};
template <typename U>
U foo(bool check)
{
U a;
if(check)
{
char ex = 'x';
a = ex;
return a;
}
else
{
a = value;
return value;
}
}
private:
T value;
};
int main()
{
int b = 5;
A <int>a1(b);
cout <<a1.foo(true) << endl;
return 0;
}
我收到此錯誤:
main.cpp: In function 'int main()':
main.cpp:39:21: error: no matching function for call to 'A<int>::foo(bool)'
cout <<a1.foo(true) << endl;
^
main.cpp:11:7: note: candidate: 'template<class U> U A<T>::foo(bool) [with U = U; T = int]'
U foo(bool check)
^~~
main.cpp:11:7: note: template argument deduction/substitution failed:
main.cpp:39:21: note: couldn't deduce template parameter 'U'
cout <<a1.foo(true) << endl;
當我在類中顯式聲明該函數時,它找不到該函數。 我試圖將其轉換為所需的格式。 它仍然給我錯誤。
我是模板新手。 我要去哪里錯了? 請不要只修復我的代碼。 向我解釋一下您所做的詳細更改。
編輯 :謝謝您的回答。 我有人問我為什么要問這個問題。 這里還有一些背景
我正在嘗試制作一個定制的數組,該數組可以接受從標准數據類型到數組和對象的任何數據類型。 該數組索引從1開始。 但是,第零個元素是一個無符號整數,具有此數組中元素的數量。 我有一個稱為“ GetElementAt”的函數,它將在某個索引處獲取元素。 我現在遇到的問題是,如果元素編號為0,我希望此函數返回無符號整數(元素數量),然后返回數據類型T
(數組中數據類型為T的元素之一),否則。
foo
是模板類中的方法模板。 因此,由於必須為a1
定義模板參數,因此也必須為foo
指定模板參數:
a1.foo<char>(true);
無法對返回類型進行模板參數推導。 您需要指定模板參數
a1.foo<int>(true) // if U needs to be an int
或使用類中的T
,您正在對類型U
和T
的變量進行賦值,因此可能正是您所需要的。
template <class T>
class A
{
public:
A(T& arg): value(arg) {};
T foo(bool check)
{
// ...
}
// or alternatively:
template <typename U = T>
U foo(bool check)
{
// ...
}
private:
T value;
};
我想你要:
template <class T>
class A
{
public:
A(const T& arg): value(arg) {};
template <bool check>
auto foo()
{
if constexpr (check) {
return 'x'; // char
} else {
return value; // T
}
}
private:
T value;
};
用法:
std::cout << a1.foo<true>() << endl; // x
std::cout << a1.foo<false>() << endl; // 5
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.