模板别名有不同的返回类型
问题描述:
成员函数
如果有以下问题模板别名有不同的返回类型
class a;
class b;
class c;
class db {
...
const std::set<a*>& get_all_a();
const std::vector<b*>& get_all_b();
const custom_c_container& obtain_all_the_cs();
...
}
我还有很长的功能,需要做同样的事情(我可以写一个模板,这需要A型,B或c,为此)为这3个数据集中的每一个,并有一个db的实例。唯一的问题是数据访问。我想通过写东西的效果,解决了:
template<class data_type>
auto get_data();
template<>
std::result_of<decltype(&db::get_all_a)(db)>::type get_data<a>
= std::mem_fn(&db::get_all_a);
可能有多种原因失败了,但我希望它显示我想要实现的。
如所建议的,我将添加所期望的使用例:
template<class data_type>
void process(db& my_db) {
for(auto& item : get_data<data_type>(my_db) {
//... some processing ...
}
}
...
void process_all() {
db my_db = get_db();
process<a>(my_db);
process<b>(my_db);
process<c>(my_db);
}
答
C++ 17溶液:
template <class data_type>
decltype(auto) get_data()
{
if constexpr(std::is_same_v<data_type, a>) { return get_all_a(); }
else if constexpr(std::is_same_v<data_type, b>) { return get_all_b(); }
else { return get_all_c(); }
}
C++ 14溶液:
template <typename>
struct dispatch;
template <>
struct dispatch<a> { decltype(auto) get(db& x) { return x.get_all_a(); } };
template <>
struct dispatch<b> { decltype(auto) get(db& x) { return x.get_all_b(); } };
template <>
struct dispatch<c> { decltype(auto) get(db& x) { return x.get_all_c(); } };
template <class data_type>
decltype(auto) get_data()
{
return dispatch<data_type>{}.get(db);
}
C++ 11溶液:
template <typename>
struct dispatch;
template <>
struct dispatch<a>
{
auto get(db& x) -> decltype(x.get_all_a()) { return x.get_all_a(); }
};
template <>
struct dispatch<b>
{
auto get(db& x) -> decltype(x.get_all_b()) { return x.get_all_b(); }
};
template <>
struct dispatch<c>
{
auto get(db& x) -> decltype(x.get_all_c()) { return x.get_all_c(); }
};
template <class data_type>
auto get_data() -> decltype(dispatch<data_type>{}.get(db))
{
return dispatch<data_type>{}.get(db);
}
+0
不幸的是,该项目使用Visual Studio 2013,这意味着我或多或少局限于C++ 11。编辑:这个评论是在C++ 14解决方案进入之前编写的,我会尝试。 – user2426460
+0
@ user2426460:也增加了一个C++ 11解决方案。 –
不清楚。显示一个真实的最简单的例子,显示所需的用法 –