Const函数签名来自函数签名

const function signature from function signature

本文关键字:函数 Const      更新时间:2023-10-16
typedef void fv();
typedef std::add_const<fv>::type fvc;
typedef void fv_const() const;
static_assert(std::is_same<fvc,fv_const>::value,"Oops");

这不能编译,因为fvcfv_const不是相同的类型。

是否可能由fv导出类型fvc,使其等于fv_const ?

const添加到非成员函数签名中没有多大意义,但是您可以这样做:

template<class T> struct add_f_const;
template<class R, class...Args>
struct add_f_const<R (Args...)> { typedef R type(Args...) const; };
static_assert(std::is_same<add_f_const<void()>::type, void() const>::value, "Oops");

通常将const添加到成员函数中:

template<class T> struct add_member_const;
template<class T, class R, class...Args>
struct add_member_const<R (T::*)(Args...)> { using type = R (T::*)(Args...) const; };
struct test {};
static_assert(std::is_same<add_member_const<void (test::*)()>::type,
  void (test::*)() const>::value,  "Oops");