gpt4 book ai didi

c++ - 在传递函数指针时是否应该转发有关 noexcept-ness 的知识?

转载 作者:可可西里 更新时间:2023-11-01 18:29:35 27 4
gpt4 key购买 nike

我已经编写了以下代码来测试跨函数调用的 noexcept 传播,它似乎并没有像我想象的那样工作。在 GCC 4.7.2 中,可以有效地测试函数是否为 noexcept 仅直接或作为模板特化参数传递时;但不是当作为参数传递给模板函数时,或作为指向普通函数的函数指针时——即使该函数将其形式参数声明为noexcept。这是代码:

#include <iostream>

#define test(f) \
std::cout << __func__ << ": " #f " is " \
<< (noexcept(f()) ? "" : "not ") \
<< "noexcept\n";

template <void(*f)()>
static inline void test0() {
test(f);
}

template <typename F>
static inline void test1(F f) {
test(f);
}

static inline void test2(void(*f)()) {
test(f);
}

static inline void test3(void(*f)()noexcept) {
test(f);
}

void f1() {}
void f2() noexcept {}

int main() {
test(f1);
test(f2);
test0<f1>();
test0<f2>();
test1(f1);
test1(f2);
test2(f1);
test2(f2);
test3(f1);
test3(f2);
return 0;
}

这是输出:

main: f1 is not noexceptmain: f2 is noexcepttest0: f is not noexcepttest0: f is noexcepttest1: f is not noexcepttest1: f is not noexcepttest2: f is not noexcepttest2: f is not noexcepttest3: f is not noexcepttest3: f is not noexcept

为什么 noexceptness 在其他情况下不传播?在 test1 的情况下,整个函数是用 F 的正确类型“实例化”的,编译器此时肯定知道 F 是否是 noexcept功能。当完全忽略 noexceptness 声明时,为什么可以按照我写的方式编写 test3

标准是否必须对此有具体说明?

最佳答案

C++11 标准的第 15.4.13 节指出“异常规范不被视为函数类型的一部分”。

关于c++ - 在传递函数指针时是否应该转发有关 noexcept-ness 的知识?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14003502/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com