这是一段简单的代码:
#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)。
最佳答案
不能对返回类型进行模板参数推导。你需要指定模板参数
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;
};
关于c++ - 在模板化类中返回模板变量的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51426675/