Pointer-to-member as template parameter deduction

落花浮王杯 提交于 2019-12-23 21:37:30

问题


I want to get pointer-to-member as template parameter to the foo1. Here is code:

struct baz{
    int qux;
};

template<typename C, typename T, T C::*m>
struct foo1{};

template<typename C, typename T>
void barr2(T C::*m){
}

template<typename C, typename T>
void barr1(T C::*m){
    barr2(m); // ok
    foo1<C, T, &baz::qux> _; // ok
    foo1<C, T, m> f; // g++4.6.1 error here; how to pass 'm' correctly ?
}

int main(){
    barr1(&baz::qux);
}

So how it should look like?


回答1:


It doesn't work for you because you are trying to use run-time information in a compile-time expression. It is the same as using integer that you read from console to specialize a template. It is not meant to work.

It doesn't necessarily solve your problem, but if the intent of barr1 function was to ease typing burden, something like this may work for you:

struct baz{
    int qux;
};

template<typename C, typename T, T C::*m>
struct foo1 {};

#define FOO(Class, Member)                                  \
    foo1<Class, decltype(Class::Member), &Class::Member>

int main(){
    FOO(baz, qux) f;
}


来源:https://stackoverflow.com/questions/11182088/pointer-to-member-as-template-parameter-deduction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!