【发布时间】:2013-04-07 19:28:52
【问题描述】:
我确实有一个小问题,我想解决。
使用类模板,我使用 typeid() 检查数据类型,以便以正确的方式处理它们。
template <typename _Ty_Id,
typename _Ty_Value>
class Attribute : public AttributeBase<_Ty_Id>
{
public:
Attribute() :
AttributeBase(_Ty_Id()),
m_tyValue(_Ty_Value())
{
}
Attribute(_Ty_Id tyId, _Ty_Value tyValue) :
AttributeBase(tyId),
m_tyValue(tyValue)
{
}
virtual ~Attribute() {};
virtual _Ty_Id getId() const {return m_tyId;}
virtual _Ty_Value getValue() const {return m_tyValue;}
virtual void toXml(iolib::Xml& xmlFile)
{
std::list<std::string> listXmlData;
std::string strTag;
if(typeid(m_tyId) == typeid(std::string))
{
strTag = m_tyId;
}
else
{
strTag = core::Stringfunc::format(strTag, m_tyId, 0, 0);
}
listXmlData.push_back(strTag);
listXmlData.push_back("entrytype");
listXmlData.push_back(m_strEntryType);
listXmlData.push_back("datatype");
listXmlData.push_back(m_strDataType);
std::string strValue;
if(typeid(m_tyValue) == typeid(std::string))
{
#pragma warning(disable : 4244)
strValue = m_tyValue;
#pragma warning(default : 4244)
}
else if((typeid(m_tyValue) == typeid(float)) ||
(typeid(m_tyValue) == typeid(double)))
{
strValue = core::Stringfunc::format(strValue, m_tyValue, 0, 3);
}
else
{
strValue = core::Stringfunc::format(strValue, m_tyValue, 0, 0);
}
listXmlData.push_back(strValue);
listXmlData.push_back("/" + strTag);
xmlFile.addElement(listXmlData);
}
private:
_Ty_Value m_tyValue;
}
模板参数是一个浮点值,将在 else if 分支中处理。但是,VS 2010 会带来警告 #4244,从 float 到 std::string 的隐式转换可能无法正常工作。
到目前为止,我在它发生的地方禁用了该警告,一切都会好起来的。但是,这当然只适用于 VS2012,并且希望将我的代码用于不同的目标。
有谁知道防止警告的更聪明的方法?
编辑
所以,现在我确实发布了课程的主要部分。
问题出在方法中:toXml(iolib::Xml& xmlFile),它将接受对我的 xml 类的引用。使用的类型 (m_tyValue) 是 Attribute 类的成员。
模板参数是:std::string 代表 m_tyId,float 代表 m_tyValue。
最好的问候, 海岸
【问题讨论】:
-
不要使用 RTTI... 应尽可能避免使用。你的目标是什么?
-
嗯...我认为使用 RTTI 检查类型是一个不错的方法。我想将值写入 xml 文件。因此,无论如何它都必须是一个字符串。当模板参数是浮点或整数类型时,我使用格式方法来完成这项工作。也许这也应该处理字符串(在这种情况下什么都不做?)
-
嗯,我不是 100% 确定这一点,但依靠它从来都不是一个好方法。它会变得非常模糊。我不想让你放弃它,但为了功能,你为什么不试试你的建议呢?也许它看起来更好!?
-
请向我们展示更多代码。在我看来,这不是处理不同模板类型参数的好方法(最好是 SSCCE)。
-
你是说试试? (“你为什么不提出你的建议?”
标签: templates visual-c++ compiler-warnings