到目前为止,我有这样的事情:
struct Foo { int DoNothing() { } };
template<typename T, typename C, typename R>
T Func(C const* obj,
R (C::*mf)(),
T* maybe_unused = nullptr)
{
(obj->*mf)();
return T{};
}
Foo f;
int r = Func<int>(&f, &Foo::DoNothing); // works as expected
如何使 &Foo::DoNothing()
成为 Func(...)
的默认值?
IOW,我想传递 Foo
的一些其他成员函数
在其他时间,但在大多数情况下,我希望 DoNothing
成为默认值。我们可以安全地假设所有成员函数
我有兴趣不接受任何争论。
最佳答案
How do I make
&Foo::DoNothing()
the default forFunc(...)
?
您基本上只需指定所需的默认参数:
struct Foo { int DoNothing() const { } };
template<
typename T,
typename C,
typename R = decltype(std::declval<const C>().DoNothing())
>
T Func(C const* obj,
R (C::*mf)() const = &C::DoNothing,
T* maybe_unused = nullptr)
{
(obj->*mf)();
return T{};
}
请注意,您需要指定两个不同的东西:一个是要调用的默认成员函数,另一个是默认返回值类型,因为它不能从默认参数中推导出来。
关于c++ - 具有成员函数指针的模板的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47561562/