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

C++ 如何在C+中使用decltype引用当前类+;11?,c++,c++11,static-methods,decltype,C++,C++11,Static Methods,Decltype,当我声明一个类静态方法时,是否可以使用decltype(或任何其他类似样式)引用当前类?比如说, class AAA { static AAA const make(); }; 我正试着做这样的东西 class AAA { static decltype(*this) const make(); // Not working because there's no `this`. }; *此用于描述我想做的事情。我想知道一些decltype()表达式,可以解析为AAA 如果可

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

class
AAA
{
    static AAA const make();
};
我正试着做这样的东西

class
AAA
{
    static decltype(*this) const make();  // Not working because there's no `this`.
};
*此
用于描述我想做的事情。我想知道一些
decltype()
表达式,可以解析为
AAA


如果可能的话,我该如何做呢?

在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();
    }
};
这是低技术,但非常可读

您应该避免按值返回const限定类型。这会抑制有效的移动语义。如果要避免赋值给右值,请创建一个符合
&
条件的赋值运算符

您或许可以这样做:

#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;
}
#包括
AAA级
{
int_i;
公众:
AAA(int i):_i(i){}
静态自动生成(inti)->typename std::remove\u reference::type
{
返回{i};
}
作废打印()
{

std::cout刚刚发明了一种使用成员指针的方法,它似乎可以工作:

这也不是完美的,它需要-fppermissive使用gcc编译, 但至少gcc/VS/Intel都编译了它,而且它可以工作。
事实上,gcc/mingw甚至不需要-fppermissive。我不知道你为什么要用简洁明了的
静态AAA const make()
来交换间接
静态decltype(*this)const make())
。可读性是第一位的,明确说明您的类型对读者有很大帮助。这背后的想法是在特定的“智能”中向整个类层次结构添加
make
函数吗方法?这就是奇怪的重复模板参数模式的情况。如果这只是一个类,我不理解派生返回类型的需要,
AAA
就可以了(但是,我也不知道调用构造函数有什么错).我没有用例的具体实例。我突然对这个问题感到好奇,如果这是可能的话,我想也许我可以在以后找到一些有趣的应用程序。在这个问题上,我不认为这个想法有什么不好的地方。我也认为这没有多大用处,但这个问题困扰了我很长时间,所以我决定问此.User hvd已提出类似建议(现已删除),但不允许[expr.prim.general]/3关于表达式
:“它不应出现在可选cv限定符seq之前,也不应出现在静态成员函数的声明中”@DyP:我怀疑可能是这样。谢谢,更新帖子。

    #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();
    }