如何在C ++ 11中使用decltype引用当前类? [英] How to refer current class using decltype in C++11?

查看:115
本文介绍了如何在C ++ 11中使用decltype引用当前类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When I declare a class static method, is it possible to refer current class using decltype (or in any other similar style)? For example,

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

我正在尝试制作类似的东西。

I am trying to make something like this.

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

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

The *this is used to describe what I want to do. I want to know some decltype() expression which can be resolved to AAA.

如果可能的话我该怎么做?

If it's possible how can I do that?

推荐答案

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

In C++1y you could do this:

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

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

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

This is not legal in C++11 as you need to specify a return type for make(). In C++98/03/11 you can:

class
AAA
{
public:
    typedef AAA Self;

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

技术含量低,但可读性强。

That is low-tech, but very readable.

< aside>

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

You should avoid returning const-qualified types by value. This inhibits efficient move semantics. If you want to avoid assigning to rvalues, then create an assignment operator qualified with &.

< / aside>

这篇关于如何在C ++ 11中使用decltype引用当前类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆