【发布时间】:2015-06-11 15:43:28
【问题描述】:
考虑:
int convert_it(std::string& x)
{
return 5;
}
void takes_int_ref(int& i)
{
}
我想写一个函数,它只有在convert_it 可以应用并且结果传递给takes_int_ref 时才存在。即函数体为:
template <typename A>
void doit(A& a)
{
int i = convert_it(a);
takes_int_ref(i);
}
但是,如果我这样做:
template <typename A>
auto doit(A& a) -> decltype(takes_int_ref(convert_it(a)), void())
它不起作用,因为invalid initialization of non-const reference of type 'int&' from an rvalue of type 'int'。
我想到了以下可行的解决方案:
template <typename T>
T& gimme_ref(T t) { throw std::runtime_error("No"); return t; }
template <typename A>
auto doit(A& a) -> decltype(takes_int_ref(gimme_ref(convert_it(a))), void())
但是,这似乎很老套,decltype 不再反映函数体的作用。本质上问题似乎是decltype 只接受一个表达式,而这里的函数体中需要两个语句。
在这里采取什么正确的方法?
【问题讨论】:
-
std::result_of和std::enable_if有帮助吗?
标签: c++ templates c++11 decltype