c++ - 如何在 C++ 中注册动态成员

标签 c++

python中的魔术方法真的很神奇。例如:

class DynMember:

    def __getattr__(self, name: str):
        def fn(self, **kwargs):
            print(kwargs)

        setattr(self.__class__, name, fn)

        return lambda **x: fn(self, **x)

if __name__ == "__main__":
    d = DynMember()
    d.someFn(title="Greeting", description="Hello world!") # outputs {'title': 'Greeting', 'description': 'Hello world!'}
    d.someFn(k1="value 1", k2="value 2") # outputs {'k1': 'value 1', 'k2': 'value 2'}
没有someFnDynMember类(class)。该方法是使用 __getattr__ 在类上设置的魔术方法和setattr内置方法。这些方法非常强大,让类在 python 中创造奇迹。 (仅用 40 行代码编写了一个 html 生成器)。如何在 C++ 中实现类似的东西?

最佳答案

C++ 尚不支持您想要的功能,有一些第三方库(如 Qt 或 Boost)提供了这些功能。但是(关于你到底想要什么的含糊不清)如果你想实现类似 def fn(self, **kwargs) 的东西你可以用 Variadic Functions 来做( Example ) 或 Template Parameter Pack ( Example ) 或 Designated initializers来自 C++20 或 std::map (正如@alterigel 在 commnets 上提到的那样)。

反射:

  • How can I add reflection to a C++ application ?
  • Reflection for C++

  • 参数:
  • kwargs like arguments with Boost
  • Another implementation of kwargs like arguments
  • 关于c++ - 如何在 C++ 中注册动态成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65384778/

    相关文章:

    c++ - 避免使用 Dynamic_Cast 的正确设计

    c++ - 课外计时器

    c++ - AIX:为什么抛出异常会中止多线程代码?

    c++ - 为分配的内存设置 swappiness

    c++ - 防止带有尾随返回类型的悬空右值引用

    c++ - CMake 是否总是为所有可能的项目配置生成配置?

    c++ - 如何将 std::string 分配给我类(class)中的其他 std::string(overload = for string object)。如何加载 .ini 文件

    C++ 和 OpenMP : How to make the initializer list of a constructor critical?

    c++ - 中断主线程并要求它做一些事情

    c++ - 如何区分/分隔模板功能的两个连续可变参数模板参数包?