我正在寻找如下工作的 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);
关于c++ - 自动转换类型,当非静态函数的签名如此明显时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38493694/