c++ - 自动转换类型,当非静态函数的签名如此明显时

标签 c++ c++11

我正在寻找如下工作的 C++ 功能:-

在一定范围内,使用自定义转换器函数,C++可以自动转换所有类实例(本例中为int)到另一个类(Person),在所有函数名称和签名明显的地方。

示例

我有一个为一个人注册现金账户的功能。

void Person::addAccount(Account account){...}
//..... There are a lot of other functions of Person.
//..... This is why I want converting to be automatic.

此人有“id”。我可以从“id”查询 Person 对象

Person* PersonManager::getPerson(int id){ .... }
//id is the main "communicator" that all systems use

因此,我可以像这样向人员 ID 添加帐户:-

personManager()->getPerson(5)->addAccount(Account());

这就是我要实现的目标。 :-

class X{
    Person* super_smart_converter$$$(int id){    
        return  personManager()->getPerson(id);
    }

    void f(){
        int id=5;
        id->addAccount(Account()); //<-- I am captivated by how short it can be.
        //^ call super_smart_converter$$$ automatically 
        //   because addAccount is a unique name belongs to Person only
    }
}

C++有这样的功能,还是类似的东西?
或者...是否有任何编码技术可以实现类似的结果?

注意:我不能重载ID的运算符->(如果恰好是一个类的话),因为id用在很多不相关的地方,可以转换成很多不相关的类型。

最佳答案

你可以这样做:

template <typename T> struct tag {};

// Overloads to retrieve wanted object from id
Person& Convert(tag<Person>, int id) { return  personManager()->getPerson(id); }

// The magic function
template <typename T, typename C, typename M, typename ... Ts>
decltype(auto) super_smart_caller(T&& id, M (C::*m), Ts&&...args)
{
    auto& c = Convert(tag<C>{}, std::forward<T>(id));
    return (c.*m)(std::forward<Ts>(args)...);
}

通话可能看起来像

super_smart_caller(1, &Person::print, 42);
super_smart_caller("John", &Person::print, 0);

Demo

关于c++ - 自动转换类型,当非静态函数的签名如此明显时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38493694/

相关文章:

c++ - 函数采用指向集合的指针的优点,以避免在返回时复制?

c++ - 迭代器有什么意义?

c++ - 使用 push_back 时,std::unique_ptr 是否移入了 std::vector?

c++ - boost::program_options 的链接错误

c++ - 匹配成员函数存在和签名 : parameters

c++ - 在 Valgrind 中仍然可以访问 libcurl C++ 代码的泄漏摘要

c++ - 如何创建继承自 Release 的 CMake 配置类型

c++ - Boost.Spirit.Qi - 针对原始数据类型的边界检查

c++ - 将工作项添加到数组或列表的非阻塞方式

c++ - 为每次 c++ 创建一个障碍