c – 如何防止未实现方法的对象生成模板
发布时间:2020-12-16 10:14:37 所属栏目:百科 来源:网络整理
导读:因此,为了示例的目的,假设我有3个简单的结构,第二个不包含bar方法: struct one { void foo(const int); void bar();};struct two { void foo(const int);};struct three { void foo(const int); void bar();}; 然后我有一个结构将管理这些类型的对象: stru
因此,为了示例的目的,假设我有3个简单的结构,第二个不包含bar方法:
struct one { void foo(const int); void bar(); }; struct two { void foo(const int); }; struct three { void foo(const int); void bar(); }; 然后我有一个结构将管理这些类型的对象: struct owner { map<int,one> ones; map<int,two> twos; map<int,three> threes; template <typename T,typename Func> void callFunc(T& param,const Func& func) { func(param); } template <typename T> void findObject(int key,const T& func) { if(ones.count(key) != 0U) { callFunc(ones[key],func); } else if(twos.count(key) != 0U) { callFunc(twos[key],func); } else { callFunc(threes[key],func); } } void foo(const int key,const int param) { findObject(key,[&](auto& value) { value.foo(param); } ); } void bar(const int key) { findObject(key,[&](auto& value) { value.bar(); } ); } }; 当我尝试编译这个时,我得到:
有没有办法可以解决这个问题? Live Example 解决方法
首先,公用事业.一个是我们最喜欢的重载,展示了三个C 17特性,并重载了几个函数对象的operator(),全部分为两行.
template<class... Ts> struct overload : Ts... { using Ts::operator()...; }; template<class... Ts> overload(Ts...) -> overload<Ts...>; 然后是accept-everything回退标记类型: struct fallback_t { template<class T> fallback_t(T&&) {} }; 现在来电话本身.我们通过将value.bar()调用放入尾随返回类型来使原始泛型lambda SFINAE友好,然后使用具有未定义行为的回退重载来重载它(如果实际调用的话)(因为OP“省略[ted]任何显式定义行为”): void bar(const int key) { findObject(key,overload { [&](auto& value) -> decltype(void(value.bar())) { value.bar(); },[](fallback_t){ fire_missiles_and_impregnate_cat(); } } ); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |