- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
在模板类中,我尝试使用 dynamic_cast 从文件中读取的字符串进行转换,并希望能够使用 bad_cast 异常捕获失败的转换。但是,在编译时(将测试程序设置为 double 作为模板类,我得到 dynamic_cast 的这个错误:
datafilereader.cpp(20): error C2680: 'double *' : invalid target type for dynamic_cast
我试着把它写成 <T>
而不是 <T*>
(当我查看有关动态转换的其他问题时,后者似乎是常见的方式......),但实际上是相同的错误。
数据文件读取器.cpp
#include "DataFileReader.h"
#include <typeinfo>
template <typename T>
void DataFileReader<T>::openFiles() {
dataFileStream.open(dataFileName);
errorFileStream.open(errorFileName, ios::app);
if (!(dataFileStream.is_open() && errorFileStream.is_open()))
throw(runtime_error("Couldn't open at least one of the files."));
}
template <typename T>
bool DataFileReader<T>::readNextValue(T &aValue) {
ios_base::iostate mask = ios::eofbit|ios::failbit|ios::badbit;
dataFileStream.exceptions(mask);
while (true) {
string readValue;
try {
dataFileStream >> readValue;
aValue = dynamic_cast<T*>(readValue);
return true;
}
catch(bad_cast &bc) {
errorFileStream << readValue << " - " << bc.what() << endl;
}
catch(ios_base::failure &eo) {
if(dataFileStream.eof())
return false;
}
}
}
数据文件读取器.h
#ifndef DataFileReader_H
#define DataFileReader_H
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
template <typename T>
class DataFileReader {
private:
string dataFileName;
string errorFileName;
ifstream& dataFileStream;
ofstream& errorFileStream;
public:
DataFileReader(string aDataFileName, string aErrorFileName): dataFileName(aDataFileName), errorFileName(aErrorFileName), dataFileStream(*(new std::ifstream(""))), errorFileStream(*(new std::ofstream(""))) {};
/* pre: A file named aDataFile contains values to read. */
~DataFileReader() {dataFileStream.close(); errorFileStream.close(); delete dataFileStream; delete errorFileStream;}
/* post: Files are closed */
void openFiles(); // throw (runtime_error);
/* post: An input stream from the file named aDataFile and an output stream to the file named aErrorFile are opened.
If either of these operations fails a runtime_error exception is thrown. */
bool readNextValue(T &aValue);
/* pre: openFiles has been successfully called.
post: If a value has been successfully read, aValue holds that value and true is returned.
Else, the read operation encountered an end-of-file and false is returned. */
};
#endif
数据测试类.cpp
#ifndef DataTestClass_H
#define DataTestClass_H
#include "DataFilter.cpp"
#include "DataFileReader.cpp"
#include <iostream>
#include <fstream>
#include <string>
#include <exception>
#include <vector>
//---------------------------------------------------------------------------
vector<double> vec;
int rangeErrorCounter = 0;
void printResults() {
double summa(0), medel(0);
vector<double>::iterator first, last, it;
first = vec.begin();
last = vec.end();
for (it = first; it != last; ++it)
summa += *it;
medel = summa/vec.size();
cout << "Lästa numeriska värden:\t" << vec.size()+rangeErrorCounter << endl;
cout << "Värden utanför intervallet:\t" << rangeErrorCounter << endl;
cout << "Summa:\t\t\t" << summa << endl;
cout << "Medelvärde:\t\t" << medel << endl;
}
int main(int args[])
{
DataFileReader<double> dr("Values.dat", "ReadErrors.dat");
try {
dr.openFiles();
}
catch (runtime_error &rt) {
cout << "Error reading files: " << rt.what() << endl;
return 0;
}
DataFilter<double> df(&dr, 0.0, 10.0);
ofstream os("RangeErrors.dat");
if(os.is_open())
while(true) {
double value;
try {
while(df.getNextValue(value))
vec.push_back(value);
printResults();
os.close();
return 0;
}
catch(range_error) {
rangeErrorCounter++;
os << value << endl;
}
}
else
cout << "Couldn't open RangeErrors.dat" << endl;
}
#endif
数据过滤器.cpp
#include "DataFilter.h"
template <typename T>
bool DataFilter<T>::getNextValue(T &aValue) {
if (fileReader.readNextValue(aValue)) {
if (aValue > max || aValue < min)
throw(range_error("Outside of range"));
return true;
}
return false;
}
数据过滤器.h
#ifndef DataFilter_H
#define DataFilter_H
#include "DataFileReader.h"
template <typename T>
class DataFilter {
private:
DataFileReader<T> fileReader;
T min, max;
public:
DataFilter(DataFileReader<T> *aReader, T aMin, T aMax): fileReader(*aReader), min(aMin), max(aMax) {};
/* pre: aReader points to an instance of DataFileReader<T> for which openFiles() has been succesfully called. */
bool getNextValue(T &aValue); // throw (range_error);
/* pre: an earlier call to getNextValue() has not returned false.
post: true is returned if aValue holds a value read from aReader. If a value could not be read, false is returned.
If a value is read but is not within the interval specified by aMin and aMax parameters to the constructor, a range_error exception is thrown. */
};
#endif
感谢任何帮助。在 SO 和 Google 上搜索了几个小时后,我仍然感到困惑...
最佳答案
您不能使用dynamic_cast
将string
变量转换为不是从string
派生的数据类型。这样做是一个编译时错误,您无法在运行时捕获它。
如果你想将一个string
值解析成不同的类型,使用istringstream
,例如:
if (!(dataFileStream >> readValue)) // did I/O fail?
return false;
istringstream iss(readValue);
if (!(iss >> aValue)) // did parsing fail?
return false;
return iss.eof(); // was the entire value consumed?
关于c++ - dynamic_cast 模板类 "invalid target type for dynamic_cast",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26050823/
我正在尝试向 iOS 应用商店提交更新。我要从 Buzztouch 应用程序转到 Sprite Kit 应用程序。我能够存档 Xcode 项目并提交它。该应用程序的状态为“上传已收到”,但大约一分钟后
我收到了这个奇怪的警告。我不确定是什么原因造成的。 .dia文件扩展名应该表示核心有向图图形文件。我没有添加,应用程序几乎没有用户界面。 最佳答案 我对这个答案并不满意,但我认为它可以帮助人们,直到找
下面用作 Uri 参数的程序集限定字符串在 XAML 中工作,但在代码中使用时会出现错误。 我尝试了各种 UriKind,结果都相同。我该如何解决这个问题? [Test] public void La
我正在开发一个 Angular 应用程序,目的是将其部署到移动设备和 Web 浏览器上。设置表单样式以显示无效输入时,我应该定位 Angular“ng-invalid”类还是 HTML5“:inval
我有一个在 Google App Engine 上运行的应用程序,它是 Android 应用程序的后端。它基本上是 Android 应用程序和在我自己的服务器上运行的 MySQL 数据库之间的桥梁。
我的代码是这样的: func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle,
I need to encrypt using Python with the A256GCM algorithm, and getting back a JWT that I need to
无法成功编译webpack并生成bundle.js文件。据我了解,我的 src_dir 和 dist_dir 变量能够指向正确的路径,但在尝试编译时我仍然始终收到两个错误之一。 配置对象无效。 Web
因此,当我在 postgres 上运行 regexp_matches 时收到一条错误消息,并且无法弄清楚如何通过它。它似乎在 regex101 等 reg_exp 测试站点上运行良好,但不幸的是在实际
这些是我正在使用的导入: import com.novell.ldap.*; import java.io.UnsupportedEncodingException; 我正在尝试进行一个非常简单的密码
在记录器函数的简写情况下,Pylint 提示 Invalid constant name "myprint"(invalid-name)。 # import from utils import get
我试图创建一个HTML输入标签,该标签仅接受以2种格式之一输入的数字,并拒绝所有其他输入。 我只想接受以下格式的数字,包括破折号: 1234-12 和 1234-12-12 注意:不是日期,而是合法的
我一直在尝试使用 Bootstrap 的表单样式处理 AngularJS 的电子邮件验证,并遇到了这个 CSS block 。 input:focus:required:invalid, textar
我正在编写一个程序,以确保我了解如何在 C 中正确实现单向链表。我目前正在哈佛的 CS50 类(class)中学习,并且使用本教程,因为 CS50 人员不解释链接详细列出数据结构:https://ww
此问题与询问同一消息的另一个问题不重复,但在另一个上下文中。这个问题的上下文只是关于上传截图图像和获取消息。 今天,我在将图片上传到 App Store Connect 时收到一条新消息: Inval
我的代码似乎运行良好,但当我滑动以删除 UITableView 中的一行时,应用程序崩溃并显示以下内容: 错误 LittleToDoApp[70390:4116002] *** Terminating
当我尝试发送语音消息时,总是收到无效的url错误。我正在使用Whisper将音频转换为文本,但由于某种原因,我似乎无法将文件传递给Whisper。当我在Java脚本中使用它而不是在TypeScrip中
我正在尝试在 flutter 上对 http 客户端进行单元测试。在模拟 http 和我的存储库类之后: void main() { MockHttpCLient mockHttpCLient;
我正在使用 pandoc 作为一个库,相关的代码片段是: module Lib ( latexDirToTex, latexToTxt ) where import qualified
我正在开发一个(相对简单的)Rails应用程序。我正在使用Devise gem处理用户 session 。每当我导航到localhost:3000/users/sign_in时,我都会看到Devise
我是一名优秀的程序员,十分优秀!