无法在模板参数中进行函数调用

Unable to make function call in template argument

本文关键字:函数调用 参数      更新时间:2023-10-16

下面的程序编译得很好。

#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
$

但是下面的程序编译失败。

#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;
^

据我说,这两个C++程序都是等效的。为什么第二个不编译,而第一个编译?

更新

一些答案是说std::sqrt()通常不声明为constexpr但在 gcc 上通过声明它constexpr来扩展它。但它仍然没有回答我的问题。

如果std::sqrt()没有声明为constexpr,那么两个程序都应该无法编译。

如果std::sqrt()在 gcc 中声明为constexpr,则两个程序都应该成功编译。

为什么只有第一个程序编译,而第二个程序失败?

第一个程序可能会为您编译,但它不可移植,因为std::sqrt函数未由要constexpr的标准指定。海湾合作委员会似乎已决定将其constexpr

template<typename _Tp>
inline _GLIBCXX_CONSTEXPR
typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
sqrt(_Tp __x)
{ return __builtin_sqrt(__x); }

但是另一个标准库实现可能没有constexprstd::sqrt函数,因此您的第一个程序不会在那里编译。

相反,让我们简化代码,并对其进行一些修改,以便完全涉及相关概念:

constexpr std::size_t r = 10.0;
std::bitset<r> b1;      // OK
std::bitset<10.0> b2;   // ill-formed

看起来b1b2的声明应该以相同的方式处理,但模板参数的隐式转换规则比其他地方的隐式转换规则更严格。

根据标准,当模板参数的类型(此处,double)与它被传递到的模板参数的类型(此处,std::size_t)不同时,只允许一组有限的转换,即"转换后的常量表达式中允许的转换">([temp.arg.nontype]/5)。根据 [expr.const]/3,转换后的常量表达式只能涉及以下转换:

  • 用户定义的转换
  • 左值到重值转换
  • 整体促销
  • 缩小转换范围之外的积分转换

在此上下文中不允许浮点积分转换,即使在r的初始化中也允许这样做。