我试图从函数的参数中扣除函数中stl容器的类型,但它不编译:
auto battery_capacity( const vector<double>& v) -> decltype(v)::value_type {
decltype(v)::value_type b=0;
return b;
}错误:
main.cpp:10:52: error: 'decltype(v)' (aka 'const vector<double> &') is not a class, namespace, or scoped
enumeration
auto battery_capacity( const vector<double>& v) -> decltype(v)::value_type {
^
main.cpp:11:3: error: 'decltype(v)' (aka 'const vector<double> &') is not a class, namespace, or scoped enumeration
decltype(v)::value_type b=0;不过,这一汇编如下:
double battery_capacity( const vector<double>& v) {
vector<double> s=v;
decltype(s)::value_type b=0;
return b;
}更新(1)
在使用模板时,根据Kerrek的答案添加:
template <typename T>
auto battery_capacity( const T& v) -> typename std::remove_reference<decltype(v)>::type::value_type {
typename std::remove_reference<decltype(v)>::type::value_type b=0;
return b;
}发布于 2014-07-06 20:18:15
如果您真的必须在这个非常简单的代码中强制使用decltype (我称之为误入歧途),那么如下所示:
auto battery_capacity(const vector<double> & v) -> std::remove_reference<decltype(v)>::type::value_type
{
std::remove_reference<decltype(v)>::type::value_type b = 0;
return b;
}如果您不知道为什么要写这个,那么您根本就不想使用decltype。这是一个非常专门的工具,用于一种非常专门的通用库写作,而不是普通的家庭使用。
当然,更简单的答案是编写double battery_capacity(...),因为您已经知道类型了!(如果你不知道类型,那么你就没有问对的问题,你的问题也没有反映出你的实际问题。)
在C++14中,您可以稍微短一点:
auto battery_capacity(const vector<double> & v)
{
return std::remove_reference_t<decltype(v)>::value_type { 0 };
}https://stackoverflow.com/questions/24599894
复制相似问题