In programming, about referring to yourself in the definition part.

Asked 2 years ago, Updated 2 years ago, 124 views

Hello.

I understand that many of the programming languages can refer to themselves while defining a function or class.

Recursive Function.

# Python3

sum = 0;

def factorial(a, n)
    if (n==1):
        return 1
    else:
        return factorial(a-1, n-1)

How can we use a factor function in the definition of a factor function?

I actually want to ask because there's actually this code.

// CPP 14
struct Bye : PassInfoMixin<Bye> {
 // // Some codes..
}

How can I inherit a template class that uses a structure called Bye while defining a structure called Bye?

What is this called in programming terms?

I can't find it easily even if I try to search it, so I'm leaving a question like this.

Thank you.

c++ programming programming-language

2022-09-20 20:46

1 Answers

How can we use a factor function in the definition of a factor function?

Each language has a scoping rule such as static scope, dynamic scope. The scope rule determines which identifier (variable name, class name, function name, etc.) refers to and binds to.

These rules determine which identifiers are accessible in an area and which objects are bound to them.

You can call factorial within factorial because the globally defined function is accessible within a lower range of factorial.

The reason why the variables named a and n do not conflict during a recursive call of factual is because a new a and n are created for each call, which has a name but is distinct from the variables in the parent call.

How can I inherit a template class that uses a structure called Bye while defining a structure called Bye?

What is this called in programming terms?

The template is instantiated when the template factor is determined and used. For a class template, even if the template factor is determined, the member function is not instantiated until it is used.

Using these properties, the way in which a parent class is determined to be a template factor and a property or something is determined is called CRTP.

The content of the PassInfoMixin class template is determined and used as a template factor in the inheritance process, so instantiation proceeds and inherits. However, as I mentioned above, the member function of PassInfoMixin<Bye> is instantiated when used. This member function will usually be used in the next line after the Bye is defined, so the member function will be instantiated without any problems and can be used without any problems.

For example, a proper polymorphism implementation, such as the following, would be an example of CRTP.

template<typename T>
struct IPrinter {
    void print() { static_cast<T*>(this)->doPrint(); }
};
struct PrintImpl : IPrinter<PrintImpl> {
    void doPrint() { std::cout << "hello\n"; }
};

PrintImpl t;
t.print();


2022-09-20 20:46

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.