【发布时间】:2013-04-18 06:51:03
【问题描述】:
我想避免在调用模板成员函数时指定返回类型。 'decltype' 关键字与 'auto' 结合可以实现这一点,但不幸的是,我们没有适用于我们需要支持的所有平台的 C++11 编译器。使用类型限定模板方法应用程序也可以,但需要调用者...使用类型限定模板方法。
以下是否可能,有一些模板魔法? boost 1.48 在这里提供任何帮助吗?
我们的实际代码是利用 boost::thread、boost::packaged_task 和 boost::unique_future,但这里是一个人为的例子:
#include <functional>
#ifdef WONT_COMPILE
struct WrapNoDecltype
{
WrapNoDecltype() {}
template<typename F>
std::result_of<F>::type // warning: 'std::result_of<_Fty>::type' : dependent name is not a type
operator()(const F& f)
{
setup();
std::result_of<F>::type result = f();
teardown();
return result;
}
void setup() { }
void teardown() { }
};
#endif
struct Wrap
{
Wrap() {}
template<typename F>
auto operator()(const F& f) -> decltype(f())
{
setup();
typename std::result_of<F()>::type result = f();
teardown();
return result;
}
void setup() { }
void teardown() { }
};
struct WrapWithReturnType
{
WrapWithReturnType() {}
template<typename RetType>
RetType
apply(const std::function<RetType(void)>& f)
{
setup();
RetType result = f();
teardown();
return result;
}
void setup() { }
void teardown() { }
};
int answer()
{
return 42;
}
int main()
{
Wrap w;
WrapWithReturnType wwr;
#ifdef WONT_COMPILE
WrapNoDecltype wna;
#endif
int i = w(answer);
int j = wwr.apply<int>(answer);
#ifdef WONT_COMPILE
int k = wna(answer);
#endif
return 0;
}
【问题讨论】:
-
您需要
typename来避免警告(甚至应该是错误),例如typename std::result_of<F>::type。 -
@DyP 错误的问题?据我所知,这个问题并没有这么说。它说
std::result_of适用于类型,而不是函数实例,这与您所说的不同...... -
@Yakk ?? OP 的代码中有一条注释说明存在警告,并且在
main函数中将非成员函数传递给operator (),因此std::result_of使用非成员函数的类型进行实例化 -
@Yakk 还是我的参考? answer 声明
std::result_of不适用于非成员函数(函数类型);该问题的OP也有类似的问题。 -
@DyP 您似乎误读了答案。它声明它不适用于 instances 函数。它声明它适用于类型的函数。
标签: c++ templates generics functor