使用 C++17/C++20 x64 gcc/clang 构建时,以下代码段会产生编译错误,而通过直接取消引用迭代器*std::max_element(std::begin(arr), std::end(arr))工作正常。关于为什么的任何想法?我还观察到了自 C++20 以来已成为 constexpr 的其他标准算法的类似行为,例如std::upper_bound
int main()
{
constexpr std::array<int,5> arr = {1,2,3,4,5};
constexpr auto it = std::max_element(std::begin(arr), std::end(arr));
}
Run Code Online (Sandbox Code Playgroud)
source>:11:73: error: '(((std::array<int, 5>::const_pointer)(& arr.std::array<int, 5>::_M_elems)) + 16)' is not a constant expression
11 | constexpr auto it = std::max_element(std::begin(arr), std::end(arr));
|
Run Code Online (Sandbox Code Playgroud) 在这次演讲中,作者提到了生命周期扩展规则扩展到基于标准的成员初始值设定项。但我看到相反的情况,即在~Y下面打印“Hello”之前调用。作者是否指的是其他东西?
#include <iostream>
using namespace std;
struct Y {
~Y() {
cout << __PRETTY_FUNCTION__ << "\n";
}
Y() {
cout << __PRETTY_FUNCTION__ << "\n";
}
};
struct X {
~X() {
cout << __PRETTY_FUNCTION__ << "\n";
}
X(const Y& y) : ref(y) {
cout << __PRETTY_FUNCTION__ << "\n";
}
const Y &ref;
};
Y gety() {
return {};
}
X getx() {
return gety();
}
int main() {
const X &ref = X{Y{}};
cout << "Hello\n"; …Run Code Online (Sandbox Code Playgroud) 如何构造具有非类型模板参数的元组
template <auto... args>
void func()
{
std::tuple<decltype(args)...> t(args...);
cout << get<3>(t) << endl;
}
template <auto... args>
struct ZZ
{
std::tuple<decltype(args)...> t(args...);
};
int main()
{
func<1,2,3,4>();
ZZ<1,2,3> z;
}
Run Code Online (Sandbox Code Playgroud)
虽然它适用于func它不适用于结构并导致编译错误(gcc主干)
vs.cc:102:35: error: ‘args’ is not a type
102 | std::tuple<decltype(args)...> t(args...);
| ^~~~
Run Code Online (Sandbox Code Playgroud) 我有一个关于使用const变量作为模板参数的问题。
使用 gcc 和 clang x64 trunk可以很好地编译以下内容:
template <int N>
void func() { }
int main(int argc, char *argv[]) {
const int x = 12;
func<x>();
}
Run Code Online (Sandbox Code Playgroud)
然而,正如人们所预料的那样,这个版本main()无法编译:
int main(int argc, char *argv[]) {
const int x = argc;
func<x>();
}
Run Code Online (Sandbox Code Playgroud)
不应该x被要求吗constexpr?或者,当该值可以在编译时确定时,是const隐式的吗?constexpr