c++ - constexpr 函数在编译时获取值,即使我的变量不是 constexpr

标签 c++ c++17

我正在尝试使用 https://github.com/gdelugre/literal_ipaddr它说它是一个

C++17 constexpr implementation of inet_addr / inet_aton / inet_pton

当我这样做时:

auto ipSourceAddressTest = IPAddr::inet_pton<AF_INET>("127.0.0.1");
std::cout << "ipSourceAddressTest is " << ipSourceAddressTest.s_addr << std::endl;

这很好用。我得到十进制的 IP 地址。

但是:

std::string ipv4address;
//get ipv4address from world here
const unsigned int ipMaxSize = 200;
char ip[ipMaxSize];
std::copy(ipv4address.begin(), ipv4address.end(), ip);
auto ipSourceAddress = IPAddr::inet_pton<AF_INET>(ip);
std::cout << "ipSourceAddress is " << ipSourceAddress.s_addr << std::endl;

请记住 ipSourceAddress.s_addruint32_t。我打印的值不是十进制的 IP,而是 4294967295,即二进制的 111...111。所以我认为它是在编译时而不是运行时获得它的值(value)。

如果我这样做

constexpr auto in_addr1 = IPAddr::inet_pton<AF_INET>(ip);

那么它的值将在编译时推导是可以理解的。但是我没有在我的变量声明中使用 constexprauto 是否意味着 constexpr

根据 https://en.cppreference.com/w/cpp/language/constexpr ,

A constexpr specifier used in a function or static member variable (since C++17) declaration implies inline

那么为什么函数 inet_pton 在编译时获取它的值?

最佳答案

ipSourceAddress在编译时没有得到它的值(就像不遵守规则一样)。

ip的值在常量表达式中不可用,因为它未声明 constexpr并且不符合常量表达式中左值到右值转换规则的其他异常(exception)之一。因此IPAddr::inet_pton<AF_INET>(ip)不是常量表达式。

你可以通过制作ipSourceAddress清楚地看到这一点constexpr (auto 并不暗示)。

constexpr在变量上需要在编译时初始化,因为初始化器不是常量表达式,所以它会失败。

参见 godbolt .

我不知道你是怎么得出不同结论的。


但是请注意,库似乎确实需要 char传递给它的数组与它包含的字符串一样长(加上空终止符)。如果您将一个更长的数组交给它并输出您看到的值,它就会失败。

参见 godbolt .

看来作者打算只用字符串文字直接调用这些函数。

关于c++ - constexpr 函数在编译时获取值,即使我的变量不是 constexpr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59384084/

相关文章:

java - 使用 JNA 访问包含 vector<char*> 的结构

c++ - 为什么 pA、pB、pC 不相等?

c++ - QtCreator 和 CMake : debug a release build

c++ - period 必须是 C++17 chrono 库中 ratio 的特化吗?

c++ - 如何让 C++ 更喜欢将 char* 转换为 string_view 而不是 bool?

c++ - 如何在 Visual Studio 中启用 C++17 编译?

c++ - const char* 不能用作 std::char_traits<char>::length 的常量值

c++ - C++ 是否支持 strnlen 函数,在 codeblocks ide 上?

c++ - 缩短嵌套的命名空间名称

c++ - std::bool_constant 背后的基本原理