C++ <>;::应用于成员指针时键入 模板 结构类{ const C&obj;//任何类 const F&fn_;//指向C的成员字段的指针 _fooClass(C&obj,F fn):obj_j(obj),fn_j(fn){} 自动运算符()()->d
<>;::应用于成员指针时键入C++ <>;::应用于成员指针时键入 模板 结构类{ const C&obj;//任何类 const F&fn_;//指向C的成员字段的指针 _fooClass(C&obj,F fn):obj_j(obj),fn_j(fn){} 自动运算符()()->d,c++,c++11,C++,C++11,<>;::应用于成员指针时键入 模板 结构类{ const C&obj;//任何类 const F&fn_;//指向C的成员字段的指针 _fooClass(C&obj,F fn):obj_j(obj),fn_j(fn){} 自动运算符()()->decltype(obj.*fn){ return obj.*fn_;//返回存储在此成员中的值 } //声明一个转换 //从fooClass到decltype(obj.*fn) }; 模板 // //版本1:让编译器推断类型 //自动f
模板
结构类{
const C&obj;//任何类
const F&fn_;//指向C的成员字段的指针
_fooClass(C&obj,F fn):obj_j(obj),fn_j(fn){}
自动运算符()()->decltype(obj.*fn){
return obj.*fn_;//返回存储在此成员中的值
}
//声明一个转换
//从fooClass到decltype(obj.*fn)
};
模板
//
//版本1:让编译器推断类型
//自动fooClass(C对象、常数F和fn)
//结果:编译
//
//版本2:显式写类型b/c编译器未实现自动返回类型推断
//自动fooClass(C对象,常量F&fn)->typename std::result\u of::type
//结果:错误(g++)无法将“const int”左值绑定到“std::_success_type::type{aka int&&}”
//错误(VC)无法将常量int转换为int&
//
自动fooClass(C对象,常量F&fn)->typename std::result\u of::type{
_c类食品(obj,fn);
返回c();
}
int main(int argc,字符**argv)
{
常数B{1};
//自动x=foo(b,&b::field2);
自动x=fooClass(b和b::field2);
std::cout对于
的result\u,值类别很重要。您的实际调用是在一个const C
左值上,所以const C&
而不是C
。此外,您到处都有悬空的引用。最后,您要寻找的是@T.C。我编辑了这个问题以显示用户函数中的用法。您能解释一下吗有悬挂的参考文献吗?
template<class C, class F>
struct _fooClass {
const C& obj_; // any class
const F& fn_; // pointer to member field of C
_fooClass(C& obj, F fn) : obj_(obj), fn_(fn) {}
auto operator()() -> decltype(obj_.*fn_) {
return obj_.*fn_; // returns the value stored in this member
}
// declare an operator that converts
// _fooClass to decltype(obj_.*fn_)
};
template<class C, class F>
//
// version 1: let compiler deduce the type
// auto fooClass(C obj, const F& fn)
// result: compiles
//
// version 2: explicit write down the type b/c compiler hasn't implemented auto return type deduction
// auto fooClass(C obj, const F& fn) -> typename std::result_of<decltype(fn)(C)>::type
// result: error (g++) cannot bind 'const int' lvalue to 'std::__success_type<int&&>::type {aka int&&}'
// error (VC) cannot convert const int to int&
//
auto fooClass(C obj, const F& fn) -> typename std::result_of<decltype(fn)(C)>::type {
_fooClass<C, F> c(obj, fn);
return c();
}
int main(int argc, char **argv)
{
const B b{1};
//auto x = foo(b, &B::field2);
auto x = fooClass(b, &B::field2);
std::cout << x << std::endl;
return 0;
}
struct B {
int field1;
}
template<class Enumerator>
void user_function(Enumerator e) {
for (auto i : e) {
}
}
// what's the return type?
template<class CONTAINER, class F>
auto enumerate(CONTAINER& c, F fn) {
return ....; // create an enumerator
}
void main() {
vector<B> vec;
user_function(enumerate(b, &b::field1));
}