在模板化类中返回模板化变量的方法

A method returning a templated varible inside a templated class?

本文关键字:方法 变量 返回      更新时间:2023-10-16

这是一个简单的代码:

#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,您正在UT类型的变量之间进行赋值,因此它可能是您所需要的。

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;
};

foo是模板类中的方法模板。因此,由于您必须为a1定义模板参数,因此您也必须指定foo的模板参数:

a1.foo<char>(true);

我想你想要:

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