代码之家  ›  专栏  ›  技术社区  ›  Oliv

int(int)&或int(int)const是什么类型?

  •  6
  • Oliv  · 技术社区  · 7 年前

    std::is_function 专用于具有以下特征的类型:

    int(int) &
    

    std::is_function

    但这既不是指向成员方法的指针,签名可以是:

    int(T::*)(int) &
    

    也不能作为对函数的引用:

    int (&)(int)
    

    那么这个奇怪的签名是什么?

    3 回复  |  直到 7 年前
        1
  •  13
  •   Community CDub    4 年前

    它是一种只存在于类型系统中的函数类型。它永远无法创建。

    int(T::*)(int) &
    

    #include <type_traits>
    
    struct T { };
    using A = int(int) &;
    using B = A T::*;
    using C = int(T::*)(int) &;
    
    static_assert(std::is_same_v<B, C>);
    

    @T、 C.提及 PR0172R0

        2
  •  6
  •   SJL    7 年前

    在您链接到的文档页面上,您将看到以下评论:

    // specialization for function types that have ref-qualifiers
    

    在列表上方,您引用的示例来自。

    here .

    简而言之,它们类似于 const

    struct foo
    {
        void bar() & { std::cout << "this is an lvalue instance of foo" << "\n"; }
        void bar() && { std::cout << "this is an rvalue instance of foo" << "\n"; }
    };
    
    int main(int argc, char* argv[])
    {
        foo f{};
        f.bar();            // prints "this is an lvalue instance of foo"
        std::move(f).bar(); // prints "this is an rvalue instance of foo"
    
        return 0;
    }
    

    我想不出这个特性有什么好的用例,但可以使用。

        3
  •  5
  •   AnT stands with Russia    7 年前

    typedef int F() const;
    

    尽管上述声明没有立即涉及任何类,但后面的 const 在这种情况下,只能作为非静态类成员函数的常量限定。这将上述typedef名称的使用限制为类成员声明。例如,可以如下使用

    struct S {
      F foo;              // Declares an `int S::foo() const` member function
    };
    
    int S::foo() const {  // Defines it
      return 42;
    }
    
    F S::*p = &S::foo;    // Declares 'p' as `int (S::*)() const` pointer
    

    请注意,无论多么模糊,这是C++的一个“经典”特性,在该语言中已经存在很长时间了。

    ref-qualifier 代替