我正在为包装器实现一个模板,如:
从上面的链接中获取的包装是:
template<typename Fn, Fn fn, typename... Args>
typename std::result_of<Fn(Args...)>::type
wrapper(Args&&... args) {
return fn(std::forward<Args>(args)...);
}
#define WRAPPER(FUNC) wrapper<decltype(&FUNC), &FUNC>
给定两个函数foo和foo2:
int foo (int a) {return a};
template <class T>
T foo2(T a)
{
return a;
}
WRAPPER(foo)(4) /*Works*/
WRAPPER(foo2)(4) /*Doesn't work*/
我明白这是因为 decltype(&FUNC)
无法确定,除非模板函数被赋予其参数' types. The thing is that the information is there at compile time, ie. foo2 is called with an int, so is of type int (int) etc. etc. Isn' t有某种方式表达事物,以便用参数的类型确定函数的类型?
简化
我在上面的代码中删除了模板调用以隔离包装器部分,因此可以在同一“级别”访问函数及其参数:
template<class F, typename... Args>
typename std::result_of<F(Args...)>::type wrapper2(F&& fn, Args&&... args)
{
return fn(std::forward<Args>(args)...);
}
wrapper2(foo, 4) /*works*/
wrapper2(foo2, 4) /* the instance of foo2 to create cannot be determined */
理想情况下,包装器应该能够在给定参数列表类型的情况下创建 foo2
的正确实例 .