获得正确的value_type

时间:2011-11-17 09:14:41

标签: c++ c++11 return-type decltype template-deduction

在我的班上,我有一名成员:

std::vector<std::string> memory_;

现在我想让一个fnc返回内存的第一个元素,但我不想指定std::string作为返回类型,以防后来我决定使用不同的类型来实现这个目的所以我'我试过这个,但它不起作用:

typename decltype(memory_)::value_type call_mem()
{
    return memory_[0];
}

如何以最通用的方式指定返回类型?

3 个答案:

答案 0 :(得分:3)

只要您使用标准容器,这应该有效,我认为没问题。

或者,由于它是类的成员,因此您可以使用typedef并将value_type公开为类的嵌套类型:

class demo
{
   public:
     typedef std::vector<std::string> container_type;
     typedef container_type::value_type value_type;

     value_type call_mem()
     {
         return *std::begin(memory_); //it is more generic!
     }

   private:        
     container_type memory_;
};

请注意,*std::begin(memory_)memory_[0]*memory_.begin()更通用,因为即使数组也可以使用,但在实际代码中不太可能让您受益。

答案 1 :(得分:1)

您实际上只需稍微更改格式,并使用auto关键字:

auto call_mem() -> decltype(memory_)::value_type
{
    return memory_[0];
}

答案 2 :(得分:0)

实际上你只能decltype整个表达式:

decltype(memory_[0]) call_mem()
{
    return memory_[0];
}

但请确保在memory_之前声明call_mem。 (并使用std::begin推广到其他容器,如@Nawaz所述。)