'C++ - Is it possible to use "operator overload" without objects?
What I would like to do is to use an operator such as "operator=" but without an object. I think it is not possible by default, but maybe I am missing something. A summarized code would be the following (it does not compiles, but to show the purpose);
template<uint16_t dir_>
struct Register{
static inline void equal(uint8_t _val); // <<--- This is valid but not what I want
static inline void operator=(uint8_t _val); // <<--- This is not valid, but I would like to have this syntax
};
......
Register<0x25>::equals(1);
Register<0x25> = 1; // <<--- This syntax is nicer :)
I have a project in which I use the "void equals(...)" syntax, but I want to have a more friendly syntax using the operators, a minimal compilable example of my current setup is next:
#include <stdint.h>
template<typename Type_, uint16_t Dir_>
struct Register {
static inline void equal(Type_ _val) {
*reinterpret_cast<volatile Type_*>(Dir_) = _val;
}
};
template<typename Reg_>
struct Foo {
static inline void setOn() {
tccrA_::equal(1);
}
typedef Reg_ tccrA_;
};
typedef Foo<Register<uint8_t, 0x35>> Timer1; // 0x35 is restricted, it a sample address...
int main(){
Timer1::setOn();
}
The class Register represents a memory address and writes in it with the equal function.
The class Foo represents an entity that needs to write in a memory address, using as template argument a Register type of the previous Register template class. It uses the Register::equal function statically to avoid create a Register object in memory. Also, no object of class Foo is created, saving memory.
I want to use operator= instead of the function equal to write in the memory address, but the operator needs an object, and I don't want to create any object. It's possible to do this? This is what I say:
static inline void setOn() {
tccrA_ = 1;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
