【发布时间】:2016-11-20 14:02:00
【问题描述】:
假设我有以下代码
template<class MemberFunc>
class Foo {
MyClass object_;
void call() {
auto ptr = MemberFunc{};
(object_.*ptr)();
}
};
int main() {
Foo<decltype(&MyClass::doThings)> foo;
foo.call();
}
这段代码对我来说确实崩溃了,因为 ptr 为 0。为什么成员函数构造函数返回 0?
我的解决方法如下,但它涉及代码重复。没有其他方法可以从类型构造/实例化成员函数吗?欢迎使用 C++14。
template<class MemberFunc, MemberFunc f>
class Foo {
MyClass object_;
void call() {
(object_.*f)();
}
};
int main() {
Foo<decltype(&MyClass::doThings), &MyClass::doThings> foo;
foo.call();
}
【问题讨论】:
-
我什至不明白为什么第一个 sn-p 编译。指向成员的函数是非类型模板参数,因此它不应该与模板声明中的
class一起使用。 -
@vsoftco
decltype产生一个类型 -
#define make_foo(func) Foo<decltype(func), func>()然后auto foo = make_foo(&MyClass::doThings)