【发布时间】:2018-06-22 15:58:24
【问题描述】:
我正在编写一种容器类,我想为此提供一个apply 方法,该方法评估容器内容的函数。
template<typename T>
struct Foo
{
T val;
/** apply a free function */
template<typename U> Foo<U> apply(U(*fun)(const T&))
{
return Foo<U>(fun(val));
}
/** apply a member function */
template<typename U> Foo<U> apply(U (T::*fun)() const)
{
return Foo<U>((val.*fun)());
}
};
struct Bar{};
template class Foo<Bar>; // this compiles
//template class Foo<int>; // this produces an error
最后一行产生error: creating pointer to member function of non-class type ‘const int’。 尽管我只实例化了 Foo 而根本没有使用 apply。所以我的问题是:当T 是非类类型时,如何有效地移除第二个重载?
注意:我还尝试让一个重载采用std::function<U(const T&)>。这有点工作,因为函数指针和成员函数指针都可以转换为std::function,但是这种方法有效地禁用了U 的模板推导,这使得用户代码的可读性降低。
【问题讨论】:
-
std::apply在这里可能有用。 -
如果有帮助的话,我建议不要使用成员函数指针,它们的混乱超出了想象。
标签: c++ templates function-pointers member-function-pointers