【发布时间】:2017-12-25 17:34:47
【问题描述】:
我以delegate implementation 为起点,并将其更新为使用可变模板。
我还尝试创建一个 createCallback 函数,该函数将在一个实例中创建一个 Callback 对象,但出现了一个我不完全理解的编译错误。
一个非常基本的可编译示例是这样的(为了清楚起见,我删除了 Callback 类):
template<typename R, class T, typename ...P>
class MemberCallbackFactory
{
public:
template<R (T::*Func)(P...)>
inline static void Bind(T* o)
{
//
}
};
template<typename R, class T, typename ...P>
inline void
createCallback(T* obj, R (T::*Func)(P...))
{
MemberCallbackFactory<R, T, P...>().template Bind<Func>(obj);
}
class Test
{
public:
void doSomething(int val)
{
//
}
};
int main()
{
Test t;
// Works:
MemberCallbackFactory<void, Test, int>().Bind<&Test::doSomething>(&t);
// Produces compile error:
createCallback(&t, &Test::doSomething);
return 0;
}
使用 C++11 使用 gcc4.9.2 编译此示例返回:
test2.cpp:11:28: note: template argument deduction/substitution failed:
test2.cpp:21:9: error: ‘func’ is not a valid template argument for type ‘void (Test::*)(int)’
MemberCallbackFactory<R, T, P...>().template Bind<func>(obj);
^
test2.cpp:21:9: error: it must be a pointer-to-member of the form ‘&X::Y’
test2.cpp:21:9: error: could not convert template argument ‘func’ to ‘void (Test::*)(int)’
如果我将 &Test::doSomething 作为 Func 参数传递给 createCallback 为什么我不能将其转发给 Bind 方法?不应该是正确的类型吗?
如果我将 createCallback 函数的一部分移到 main 中,它编译得很好。
【问题讨论】:
-
与其使用
std::bind或您自己的Bind()函数,不如使用std::function和lambda 表达式。 -
@user0042:这是我正在考虑的一个选项。不过,我想了解这种情况下的问题是什么。
-
在
createCallbackFunc是一个参数,即可能是一个运行时值。这就是为什么您不能将其用作模板参数的原因。
标签: c++ function c++11 templates