类中的模板函数
Template function in class
本文关键字:函数 更新时间:2023-10-16
我不知道该怎么办。我总是通过使用简单的类和简单的模板函数来得到错误。我阅读了所有其他解决方案,但它们对我没有帮助。
在其他一些类旁边,我有一个简单的类Data:
class Data{
public:
template <class T>
T dat();
int id;
union{
char c;
int i;
double d;
};
};
和函数dat:
template <class T>
T Data::dat(){
if(id == 1) return i;
if(id == 2) return d;
if(id == 3) return c;
}
正如你所看到的,我想检查id并返回int、double或char。现在我尝试在主函数中打印值,如下所示:
Data test;
test.id=1;
test.i = 12;
cout<<test.dat();
但我总是收到这样的错误信息:
Error: Could not find a match for Data::dat<Data::T>() needed in main(int, char**).
问题出在哪里??
感谢
准确地说,您希望函数的返回类型取决于它是对象中的id
字段;换句话说,动态地。模板在编译时解析,因此它们不能在这里帮忙。你必须归还类似的东西支持这种动态的boost::variant
或boost::any
打字。
使用此:
cout<<test.dat<int>();
dat()
没有涉及T
的参数,因此编译器无法从调用中推断出T
,必须显式提供,例如:
cout << test.dat<int>();
另外,请记住,必须在头文件中实现dat()
。
我不知道该怎么办。我总是在使用一个简单的类和一个简单模板函数时出错。我阅读了所有其他解决方案,但它们对我没有帮助。
在我看来,你想建立一个受歧视的联盟。
您的实现不起作用,因为模板函数的返回类型是在编译时确定的(即,在您设置id中的值并尝试调用该函数之前)
解决方案:
class Data
{
enum value_type {
int_val, char_val, double_val
} discriminator; // private (the user doesn't see this)
// this replaces your id
union{
char c;
int i;
double d;
} value;
public:
class wrong_type_error: public std::logic_error
{
public:
wrong_type_error(const std::string& msg): std::logic_error(msg) {}
};
explicit Data(const char c)
: discriminator(Data::char_value)
, value.c(c)
{
}
explicit Data(const int i)
: discriminator(Data::int_value)
, value.i(i)
{
}
explicit Data(const double d)
: discriminator(Data::double_value)
, value.d(d)
{
}
// don't put this here: int id;
// this part can be optimized to simpler (more idiomatic) code
template<typename T> T get() const; // undefined
template<> int get() const {
if(discriminator != Data::int_val)
throw wrong_type_error("Cannot return a int from Data instance");
return value.i;
}
template<> char get() const {
if(discriminator != Data::char_val)
throw wrong_type_error("Cannot return a char from Data instance");
return value.c;
}
template<> double get() const {
if(discriminator != Data::double_val)
throw wrong_type_error("Cannot return a double from Data instance");
return value.d;
}
};
客户代码:
Data test(10.5);
cout<<test.get<double>();
话虽如此,根据您的需要,您应该考虑使用boost::变体或boost::任何情况。
VS2012表示"错误C2783:"T数据::dat(void)":无法推导出"T"的模板参数
你只需要告诉函数dat
什么是T
:
cout<<test.dat<int>();
如果您传递一个模板化参数,则可以推断出模板类型,但它无法猜测返回类型。
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- 函数调用中参数的顺序重要吗
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用不带参数的函数访问结构元素
- 代码在main()中运行,但在函数中出现错误
- 内置函数可查看CPP中的成员变量
- 如何获取std::result_of函数的返回类型
- 如何在c++中为模板函数实例创建快捷方式
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗