What's going on here? Auto/constant expression/floating point

Hello,

Can someone explain why the following snippet is erronous?

1
2
3
4
5
6
7
8
9
10
11
namespace foo {
	const auto a = 2.0;
}

class Test {
public:
	Test() {}

	const static int bar = foo::a;

};


I'm receiving the following error for line 9:
error C2057: expected constant expression


The error is referring to foo::a. If I remove the .0 from foo::a's initialization (as in, it's an int, not a double), the snippet compiles fine.

Does this possibly somehow have to do with non-integral types being disallowed from having in-class initializers? However, Test::bar is an integral type...
Last edited on
Perform the conversion from double to int at compile-time (constexpr).
1
2
3
namespace foo {
    constexpr auto a = 2.0;
}

http://coliru.stacked-crooked.com/a/d4ebb9a7dea036cc

Note: Since this International Standard imposes no restrictions on the accuracy of floating-point operations, it is unspecified whether the evaluation of a floating-point expression during translation yields the same result as the evaluation of the same expression (or the same operations on the same values) during program execution.
Thanks! Didn't know about this. Unfortunately my compiler doesn't seem to support constexpr (My IDE is Visual Studio 2013).
Last edited on
Workaround:
1
2
3
4
5
6
7
8
9
10
11
12
13
namespace foo {
    
    const int ia = 2 ;
    const double a = ia / 1.0 ;
}

class Test {

    public:
    	Test() {}
    
    	const static int bar = foo::ia ;
};

http://coliru.stacked-crooked.com/a/e00a3a1dc02431e5
Topic archived. No new replies allowed.