有没有办法从作为函数参数的模板var中获取value_type?

时间:2019-06-12 13:06:22

标签: c++ templates

我正在编写一个虚拟方法,其参数之一为std::vector。在内部,我将std::unordered_setvalue_type的{​​{1}}相同。

但是,我可以更改std::vector中的value_type,并且我不想每次都更改代码内的类型。为了更好地理解我在说什么(英语不是我的母语),请参见下面的代码。

std::vector

我期望的是这样的事情:

run(std::vector<Node> &data) {
    std::unordered_set<Node> var;
}

当然,它不起作用。预先谢谢你。

编辑:非常感谢您的回答,尤其是这个答案:https://stackoverflow.com/a/56563062/11203604

函数模板的答案是不可能的:它是一个重载的函数(虚拟)。至于类模板,由于将来工作中的技术原因,我不能将其作为模板,因为它可能是公共类。

谢谢。

3 个答案:

答案 0 :(得分:5)

您可以使用decltype来获取data的类型,然后对其应用::value_type。那会给你

std::unordered_set<std::remove_reference_t<decltype(data)>::value_type> var;

注释中Evg指出std::remove_reference_t是必需的,因为data是一个引用,并且您不能将范围解析运算符应用于引用类型。

答案 1 :(得分:4)

也许只是做一个模板功能?

template <typename T>
void run(std::vector<T>&)
{
    std::unordered_set<T> set;
}

答案 2 :(得分:1)

您可以简单地将函数泛化为容器类型上的template

template<typename Container>
void run(Container const&data) const
{
    std::unordered_set<typename Container::value_type> set;
    for(auto const& x : data) {
        /* do something clever with the datum x */
    }
}

使得它可以与支持value_type的任何容器类型一起使用。

但是,传统上C ++中的通用方法是使用迭代器:

template<typename Iter>
void run(Iter begin, Iter end) const
{
    using value_type = typename std::iterator_traits<Iter>::value_type;
    std::unordered_set<value_type> set;
    for(; begin != end; ++begin) {
        const value_type&x = *begin;
        /* do something clever with the datum x */
    }
}
相关问题