The following program compiles fine.
#include <bitset>
#include <cmath>
int main()
{
const int r = std::sqrt(100);
std::bitset<r> n;
}
$ g++ -Wall -Wextra -pedantic -std=c++11 foo.cpp
$
But the following program fails to compile.
#include <bitset>
#include <cmath>
int main()
{
std::bitset<std::sqrt(100)> n;
}
$ g++ -Wall -Wextra -pedantic -std=c++11 bar.cpp
bar.cpp: In function ‘int main()’:
bar.cpp:6:31: error: conversion from ‘__gnu_cxx::__enable_if<true, double>::__type {aka double}’ to ‘long unsigned int’ not considered for non-type template argument
std::bitset<std::sqrt(100)> n;
^
bar.cpp:6:31: error: could not convert template argument ‘std::sqrt<int>(100)’ to ‘long unsigned int’
bar.cpp:6:34: error: invalid type in declaration before ‘;’ token
std::bitset<std::sqrt(100)> n;
^
bar.cpp:6:33: warning: unused variable ‘n’ [-Wunused-variable]
std::bitset<std::sqrt(100)> n;
^
According to me, both C++ programs are equivalent. Why is it that then the second one does not compile whereas the first one does?
Update
Some of the answers are saying that std::sqrt()
is generally not declared as constexpr
but on gcc has extended it by declaring it constexpr
. But it still does not answer my question.
If std::sqrt()
is not declared as constexpr
, then both programs should fail to compile.
If std::sqrt()
is declared as constexpr
in gcc, then both programs should compile successfully.
Why is it that only the first program compiles but the second one fails?