'@classmethod decorator in C++
I have the following code :
class A{
void A(){
counter++;
}
static int counter;
int mem;
public:
static int get_counter(){
this.mem = 0;
return counter;
}
};
I remember when I want to share instance and static in a function in python, I use @classmethod decorator.How can I implement it in c++?
Solution 1:[1]
In C++ there is no decorator syntax, but ways to implement similar features, such as macros and the CRTP.
To compare with Python's @classmethod, we'll need to think of a usage. As far as I know @classmethod is typically used to implement some sort of "factory pattern". For C++ in such cases, you'll only need a properly defined constructor and a static function that returns an instance of the class.
Forgive me as I didn't get it what you were trying to do by this.mem = 0, I came up with the following usage (explain your case and I'll replace it).
In Python, suppose you want something like:
class FooBar:
foo: str
bar: str
def __init__(self, foo_val: str, bar_val: str):
self.foo = foo_val
self.bar = bar_val
@classmethod
def from_string(cls, data: str):
tmp = data.split(' ', 1)
cls.foo, cls.bar = tmp[0], tmp[1]
return cls
In C++, similar functionality can be achieved by:
#include <string>
#include <utility>
class FooBar {
public:
std::string foo;
std::string bar;
FooBar(std::string foo_val, std::string bar_val):
foo(std::move(foo_val)),
bar(std::move(bar_val)) {}
static FooBar from_string(const std::string& data) {
auto pos = data.find_first_of(' ');
return FooBar(
data.substr(0, pos),
data.substr(pos + 1, data.length() - pos - 1)
);
}
};
Also, static member functions are available both by ClassName:: and by instance., while the former is preferred.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
