![](/img/trans.png)
[英]Why doesn't constexpr function returning std::string doesn't compile when outside templated class?
[英]Why is templated constexpr with std::string allowed in gcc?
為什么允許在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;
}
海灣合作委員會可能就在這里。 根據dcl.constexpr第6段:
如果constexpr函數模板的實例化模板特化或類模板的成員函數無法滿足constexpr函數或constexpr構造函數的要求,那么該特化仍然是constexpr函數或constexpr構造函數,即使調用這樣的函數不能出現在常量表達式中。 如果模板的特化不滿足constexpr函數或constexpr構造函數在被視為非模板函數或構造函數時的要求,則模板格式錯誤,無需診斷。
該程序std::string
( std::string
不是文字類型)但不需要發出診斷。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.