如何在C ++ 11中使用decltype引用当前类?

问题描述 投票:6回答:3

当我声明一个类静态方法时,是否可以使用decltype(或任何其他类似的样式)引用当前类?例如,

class
AAA
{
    static AAA const make();
};

我想做这样的事情。

class
AAA
{
    static decltype(*this) const make();  // Not working because there's no `this`.
};

*this用于描述我想要做的事情。我想知道一些可以解析为decltype()AAA表达式。

如果有可能我该怎么办?

c++ c++11 static-methods decltype
3个回答
5
投票

在C ++ 1y中你可以这样做:

class
AAA
{
public:
    static auto make()
    {
        return AAA();
    }
};

int main()
{
    AAA aaa = AAA::make();
}

这在C ++ 11中是不合法的,因为您需要为make()指定返回类型。在C ++ 98/03/11中,您可以:

class
AAA
{
public:
    typedef AAA Self;

    static Self make()
    {
        return AAA();
    }
};

这是低技术,但非常可读。

<aside>

您应该避免按值返回const限定类型。这抑制了有效的移动语义。如果要避免分配给rvalues,则创建一个使用&限定的赋值运算符。

</aside>


0
投票

你也许可以这样做:

#include<iostream>

class AAA
{
   int _i;

   public:
   AAA(int i): _i(i) {}

   static auto make(int i) -> typename std::remove_reference<decltype(*this)>::type
   {
      return {i};
   }

   void print()
   {
      std::cout << _i << std::endl;
   }
};

int main()
{
    AAA aaa = AAA::make(1);
    aaa.print();
    return 0;
}

它至少在GCC 4.7.2上编译:)


EDIT 26/11-13: The above code is not legal c++, even though it compiles with gcc, it does not with clang or icpc. My apologies.

0
投票

刚刚发明了一种使用成员指针的方法,它似乎有效:https://godbolt.org/z/v-g5z0


    #define self_test(name) \
    void dummy__##name(void) {} \
    template  static T type__##name( void (T::*func)(void) ) { return T(); } \
    typedef decltype(type__##name(&dummy__##name)) self__##name; \
    static void test( void ) { self__##name::print(); }

    struct T1 {
      self_test(X);
      static void print() { printf( "this is T1\n" ); }
    };

    struct T2 {
      self_test(X);
      static void print() { printf( "this is T2\n" ); }
    };

    int main() {
      T1::test();
      T2::test();
    }

这也不完美,它需要-fpermissive用gcc编译,但至少gcc / VS / Intel都编译它并且它可以工作。事实上,gcc / mingw甚至不需要-fpermissive。

© www.soinside.com 2019 - 2024. All rights reserved.