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?
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.
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 )
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With