开发者

Default argument of type float = gibberish

开发者 https://www.devze.com 2023-03-16 16:27 出处:网络
I have some trouble using a default argumen开发者_如何转开发t of type float: #include <wchar.h>

I have some trouble using a default argumen开发者_如何转开发t of type 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;
}

It prints -1.36867e-033 instead of the equivalence of 1e-05. What is going on here?

I'm using VC++10.

EDIT1:

Thank you all for your replies. But casting the default argument doesn't work in the following case:

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;
}

So this is definitely a bug and worth reporting?

EDIT2:

Reported this issue to Microsoft


Looks to be an issue with a default template argument and conversion between double and float. The issue doesn't occur if you aren't using templates.

Stick an "f" at the end of that default template argument such that it treats the value as a "float" instead of a double. That seems to fix it.

template<typename T>
void fun(T t = 1e-05f);

But after applying the above fix, if you declare this

fun<double>()

you get an equivalent bug. So a better fix that works for both floats and doubles is to use a cast as follows:

template<typename T>
void fun(T t = (T)(1e-05));

As to whether this is a compiler bug or "undefined behavior", I'll let the compiler gurus chime in.

0

精彩评论

暂无评论...
验证码 换一张
取 消