Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refer current class using decltype in C++11?

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`.
};

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?

like image 415
eonil Avatar asked Nov 25 '13 21:11

eonil


People also ask

What is the decltype of a function?

If the expression parameter is a call to a function or an overloaded operator function, decltype(expression) is the return type of the function. Parentheses around an overloaded operator are ignored. If the expression parameter is an rvalue, decltype(expression) is the type of expression.

What does decltype stand for?

Decltype keyword in C++ Decltype stands for declared type of an entity or the type of an expression. It lets you extract the type from the variable so decltype is sort of an operator that evaluates the type of passed expression. SYNTAX : decltype( expression )

What does decltype return?

decltype returnsIf what we pass to decltype is the name of a variable (e.g. decltype(x) above) or function or denotes a member of an object ( decltype x.i ), then the result is the type of whatever this refers to.


1 Answers

In C++1y you could do this:

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

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

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>

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>

like image 185
Howard Hinnant Avatar answered Sep 24 '22 21:09

Howard Hinnant