在模板化类中返回模板化变量的方法
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的元素之一(。
模板参数推导不能对返回类型进行。您需要指定模板参数
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;
};
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
相关文章:
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 枚举环境变量的惯用C++14/C++17方法
- 绑定派生类方法C++从实例范围之外的分隔 std::function 变量调用
- 是否可以依赖函数范围的静态变量来执行程序关闭期间调用的方法?
- 从私有成员变量的成员方法返回unique_ptr
- 在派生类中使用基类的私有成员变量的最佳方法
- 打印所有继承的类成员变量和方法
- C++方法中的引用变量
- Visual C++: MSVC vs. GCC+CLANG: 处理 lambda 捕获类成员变量,正确的方法是什么?
- 有没有一种通用的方法来实现不变量
- 有没有将变量名称转换为双指针的简短方法?
- C++:将向量传递到构造函数以创建成员变量的最佳方法?
- C++ 互斥锁可以交叉方法/变量吗?如果是这样,为什么在这里不起作用?
- 类方法变量,如果将它们存储在类本身中会更快吗?
- 将局部方法变量分配给类指针
- 列出派生类中的所有方法/变量
- 相互冲突名称的成员变量和方法变量
- C++如果我有一个对象指针,是在堆栈或堆上分配的方法变量
- 如何从另一个类访问一个类的方法/变量,而不在c++中实例化它或子类
- 指定类变量与方法变量C++