Skip to content

Instantly share code, notes, and snippets.

@hzhangxyz
Created July 29, 2025 20:15
Show Gist options
  • Select an option

  • Save hzhangxyz/8de55e7f244ae5f8f1bdaa388acb95c4 to your computer and use it in GitHub Desktop.

Select an option

Save hzhangxyz/8de55e7f244ae5f8f1bdaa388acb95c4 to your computer and use it in GitHub Desktop.
#include <format>
#include <print>
#include <string>
#include <vector>
struct Dog {
std::string name;
void Say() const {
std::print("{}: Woof!\n", name);
}
};
struct Cat {
std::string name;
void Say() const {
std::print("{}: Meow!\n", name);
}
};
struct MemberSayDecl {
void Say() const;
};
struct MemberSayImpl {
void* value;
void (*SayImpl)(void*);
void Say() const {
SayImpl(value);
}
};
struct MemberSayFatPtr {
template<typename T>
MemberSayFatPtr(T* v) :
impl{
reinterpret_cast<void*>(v),
[](void* self) {
auto obj = static_cast<T*>(self);
obj->Say();
},
} { }
MemberSayImpl* operator->() {
return &impl;
}
MemberSayImpl operator*() {
return impl;
}
private:
MemberSayImpl impl;
};
int main() {
auto c = Cat("a");
auto d = Dog("d");
auto p = std::vector<MemberSayFatPtr>{&c, &d};
p[0]->Say();
p[1]->Say();
}
@hzhangxyz
Copy link
Author

问题:

1、c++26不支持编译期动态类型,只支持编译期动态结构体,GG。。。
2、const的member function需要区分

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment