在标准论文P0092R1中,Howard Hinnant写道:
template <class To, class Rep, class Period,
class = enable_if_t<detail::is_duration<To>{}>>
constexpr
To floor(const duration<Rep, Period>& d)
{
To t = duration_cast<To>(d);
if (t > d)
--t;
return t;
}
Run Code Online (Sandbox Code Playgroud)
这段代码怎么样?问题是,operator--a std::chrono::duration不是constexpr操作.它被定义为:
duration& operator--();
Run Code Online (Sandbox Code Playgroud)
然而,这段代码编译,并在编译时给出正确的答案:
static_assert(floor<hours>(minutes{3}).count() == 0, "”);
Run Code Online (Sandbox Code Playgroud)
那是怎么回事?
我几乎可以肯定以下是 Visual Studio 编译器的错误,但很难相信我决定在这里仔细检查:
struct A {
constexpr virtual int f() { return 0; }
};
struct B : A {
constexpr auto f() { return 1.1; }
};
constexpr int g() {
B b;
A & a = b;
return a.f();
}
static_assert( g() != 1 );
static_assert( g() == 1.1 );
Run Code Online (Sandbox Code Playgroud)
g()声明为返回int类型的函数通过编译时检查g() == 1.1意味着g()实际上返回一个double值。此行为在最新的 MSVC 编译器中可以重现,在线演示: https: //gcc.godbolt.org/z/6sGET7773
由于B::f()声明不能包含auto返回类型,程序是否存在格式错误?
这个程序:
constexpr void f() { x: ; }
Run Code Online (Sandbox Code Playgroud)
由 gcc 编译,但 clang 说:
error: statement not allowed in constexpr function
Run Code Online (Sandbox Code Playgroud)
那么这个代码有效吗?
在以下示例中:
//Case 1
constexpr int doSomethingMore(int x)
{
return x + 1;
}
//Case 2
constexpr int doSomething(int x)
{
return ++x;
}
int main()
{}
Run Code Online (Sandbox Code Playgroud)
输出:
prog.cpp:在函数'constexpr int doSomething(int)'中:
prog.cpp:12:1:错误:表达式'++ x'不是常量表达式
为什么案例1被允许但案例2不被允许?