为什么在gcc中允许带有std :: string的模板化constexpr?

man*_*ler 7 c++ gcc constexpr c++14

为什么允许在gcc中编译模板版本?它是编译器错误还是与模板一起使用时实际上有效?有人可以向我解释一下吗?

它不能在godbolt.org上使用的clang或其他编译器上编译.

编译错误由constexpr中使用的字符串和字符串流生成.

#include <iostream>
#include <string>
#include <sstream>

template<typename T>
constexpr std::string func1(T a, T b) //Compiles and runs
{
  std::stringstream ss;
  ss << a << b << a+b;
  return ss.str();
}

constexpr std::string func2(int a, int b) //Compile error
{
  std::stringstream ss;
  ss << a << b << a+b;
  return ss.str();
}

int main()
{
  int a = 5;
  int b = 7;
  std::cout << func1(a,b) << std::endl;
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

小智 8

海湾合作委员会可能就在这里.根据dcl.constexpr第6段:

如果constexpr函数模板的实例化模板特化或类模板的成员函数无法满足constexpr函数或constexpr构造函数的要求,那么该特化仍然是constexpr函数或constexpr构造函数,即使调用这样的函数不能出现在常量表达式中.如果模板的特化不满足constexpr函数或constexpr构造函数在被视为非模板函数或构造函数时的要求,则模板格式错误,无需诊断.

该程序格式错误(std::string不是文字类型),但不需要发出诊断.

  • 请注意,所有compikers都符合要求; 不需要诊断并不意味着不需要诊断. (4认同)