c++ -::std::remove_cv<> 应该适用于函数类型吗?

标签 c++ c++17

我正在尝试提取成员函数的返回和参数类型,而不必费心 constvolatile重载,但在我看来,::std::remove_cv<>不适用于函数类型:

template <typename>
struct signature
{
};

template <typename R, typename ...A>
struct signature<R(A...)>
{
};

template <typename C, typename F>
constexpr auto extract_function_type(F C::* const) noexcept
{
  return signature<::std::remove_cv_t<F>>();
}

template <typename F>
constexpr auto extract_signature(F const&) noexcept ->
  decltype(&F::operator(), extract_function_type(&F::operator()))
{
  return extract_function_type(&F::operator());
}

最佳答案

不存在 const 函数类型这样的东西:

[dcl.fct]/6:

The effect of a cv-qualifier-seq in a function declarator is not the same as adding cv-qualification on top of the function type. In the latter case, the cv-qualifiers are ignored. [Note: a function type that has a cv-qualifier-seq is not a cv-qualified type; there are no cv-qualified function types. —end note]

您必须编写自己的类型特征:

template<typename T>
struct remove_cv_seq;

template<typename R, typename... Args>
struct remove_cv_seq<R (Args...) const> {
    using type = R (Args...);
};

template<typename R, typename... Args>
struct remove_cv_seq<R (Args...)> {
    using type = R (Args...);
};

struct Foo {
    remove_cv_seq<void () const>::type bar;
};

int main()
{
    Foo const x;
    x.bar(); // This will fail to compile because it tries to call non-const member function.
}

关于c++ -::std::remove_cv<> 应该适用于函数类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38767993/

相关文章:

c++ - 没有在标题中声明的模板类成员特化

c++ - 继承相关的c++编译错误

c++ - 根据类模板的类型参数自动化类模板的大小参数

c++ - 类模板的条件无效成员函数(隐式实例化有效;显式实例化失败)

c++ - 弄清楚晦涩的指针typedef

C++ 错误 : invalid conversion from 'int' to 'const char*' [-fpermissive]|

c++ - STL-Like 范围,如果我这样做会出什么问题?

c++ - 为什么 C++17 的 std::any 不允许通过 any_cast 返回可 move 值?

c++ - 使用 boost::hana 创建一个大的编译时间映射

c++ - 函数参数究竟何时被破坏?