gpt4 book ai didi

c++ - 两个不完全相同的函数指针是否兼容?

转载 作者:行者123 更新时间:2023-11-30 02:17:13 25 4
gpt4 key购买 nike

我有这些函数指针类型:

typedef int(*a)(char*);
typedef const int(*b)(char*);
typedef int(*c)(char* const);
typedef int(*d)(const char*);
typedef long(*e)(char*);
typedef int(*f)(unsigned char*);
typedef void(*g)(char*);

我知道 acconst 完全相同(至少在 C++ 中是这样)在函数原型(prototype)参数类型中被忽略。

我的问题是我是否有一个 a 类型的变量? ,以及这 7 种类型中任何一种的另一个变量,我可以将它们中的哪一种分配给第一个变量?

a foo = NULL;
(a/b/c/d/e/f/g) bar = ...;
foo = bar; // Is this UB based on the type of bar?

我能检测到它吗?

我尝试利用 template<class F> ::std::function::operator=(F&&) 的优势被定义为“此运算符不参与重载决策,除非 f 对于参数类型 Args 是可调用的...并且返回类型为 R。”

#include <iostream>
#include <functional>
#include <type_traits>

template<class T, class U>
static void _print_is_assignable(const char* const t_name, const char* const u_name) {
using function_t = ::std::function<typename ::std::remove_pointer<T>::type>;
std::cout << t_name;
std::cout << (::std::is_assignable<function_t&, U>::value ? " == " : " != ");
std::cout << u_name << '\n';
}

#define PRINT_IS_ASSIGNABLE(T, U) _print_is_assignable<T, U>(#T, #U)

typedef int(*a)(char*);
typedef const int(*b)(char*);
typedef int(*c)(char* const);
typedef int(*d)(const char*);
typedef long(*e)(char*);
typedef int(*f)(unsigned char*);
typedef void(*g)(char*);

int main() {
PRINT_IS_ASSIGNABLE(a, a); // a == a
PRINT_IS_ASSIGNABLE(a, b); // a == b
PRINT_IS_ASSIGNABLE(a, c); // a == c
PRINT_IS_ASSIGNABLE(a, d); // a == d
PRINT_IS_ASSIGNABLE(a, e); // a == e
PRINT_IS_ASSIGNABLE(a, f); // a != f
PRINT_IS_ASSIGNABLE(a, g); // a != g
PRINT_IS_ASSIGNABLE(g, a); // g == a
}

最佳答案

我已经稍微阅读了规范,我能找到的最接近的内容是第 5.2.10 节 [expr.reinterpret.cast]:

A function pointer can be explicitly converted to a function pointer of a different type. The effect of calling a function through a pointer to a function type (8.3.5) that is not the same as the type used in the definition of the function is undefined. Except that converting a prvalue of type “pointer to T1” to the type “pointer to T2” (where T1 and T2 are function types) and back to its original type yields the original pointer value, the result of such a pointer conversion is unspecified.

这似乎告诉我,不,这是未定义的行为,除非函数指针类型完全相同,我将不得不转换回原始类型。

通过一些测试,g++ 似乎不介意是否返回指针返回什么指针,并且返回类型是否为 const 限定也无关紧要,这是有道理的。在尝试处理几乎兼容的类型时,我只需要使用 std::function

关于c++ - 两个不完全相同的函数指针是否兼容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53913580/

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