【发布时间】:2011-09-25 20:51:36
【问题描述】:
我在使用 float 类型的默认参数时遇到了一些问题:
#include <wchar.h>
#include <iostream>
template<typename T>
void fun(T t = 1e-05);
template<typename T> inline
void fun(T t)
{
std::cout << t << std::endl;
}
int wmain(int argc, wchar_t* argv[])
{
fun<float>();
_getwch();
return 0;
}
它打印 -1.36867e-033 而不是等价的 1e-05。这是怎么回事?
我正在使用 VC++10。
EDIT1:
感谢大家的回复。 但是在以下情况下强制转换默认参数不起作用:
template<typename T>
void fun(T t = static_cast<T>(1e-05));
template<typename T> inline
void fun(T t)
{
std::wcout << t << std::endl;
}
int wmain(int argc, wchar_t* argv[])
{
fun<double>();
fun<float>();
_getwch();
return 0;
}
所以这绝对是一个错误并且值得报告?
EDIT2:
【问题讨论】:
-
您期望编译器发出从 double 到 float 的转换。它没有。使用“1e-5f”修复它。使用 connect.microsoft.com 报告此问题。
-
也许您的平台上需要
wcout? -
@Hans:微妙。我正要建议
fun(T t = T(1e-05)),但认为这没有必要……顺便说一句,它在 GCC 4.6 上运行良好。 -
@Kerrek:
wcout与这里有什么关系?您为什么希望这样可以解决问题? -
嗯,这个解决方法会使编译器跳闸:
template <typename T> struct def_arg { static const T value; }; template <typename T> const T default_arg<T>::value = T(1e-05); template<typename T> void fun(T t = default_arg<T>::value); template<typename T> inline void fun(T t) { std::cout << t << std::endl; }
标签: c++ visual-studio visual-studio-2010 templates visual-c++