【发布时间】:2015-04-04 14:39:18
【问题描述】:
假设我有:
struct Foo {
void a();
void b(const int& );
int c();
};
我可以创建一个函数,该函数将任意指向Foo 方法的指针作为参数:
template <typename R, typename... Formal, typename... Args>
R call(Foo* f, R (Foo::*method)(Formal...), Args&&... args) {
return (f->*method)(std::forward<Args>(args)...);
}
int gratuitous = call(&some_foo, &Foo::c);
而且我可以创建一个函数,它采用特定类型的指向Foo 方法的指针作为模板:
template <void (Foo::*method)()>
void only_for_a(Foo *f) {
(f->*method)();
}
only_for_a<&Foo::a>(&some_foo);
但是有没有办法创建一个函数,我可以在 any 指向类方法的指针上进行模板化?我希望能够做到:
works_for_anything<&Foo::a>(&some_foo);
works_for_anything<&Foo::b>(&some_foo, 42);
int result = works_for_anything<&Foo::c>(&some_foo);
【问题讨论】:
-
不,非类型模板参数必须具有固定类型。为什么要这样做?
-
template<typename T, void(T::*medhod)()>怎么样 -
@erenon 我假设你的意思是
template <typename T, T method>,但是调用者必须指定类型,例如works_almost<decltype(&Foo::b), &Foo::b>(&some_foo, 42);。但这似乎是多余的。 -
也许使用 C++1Z:
template <using typename R, using typename... Args, R(Foo::*method)(Args...)> -
呃,
using typename,谁喜欢呢?这些关键字已经被超额订阅。为什么不template <auto Method>?