【问题标题】:Template function with container type deduction带容器类型扣除的模板函数
【发布时间】:2014-02-12 12:27:33
【问题描述】:

我编写了一个函数来迭代listvector 或字符串上带有iterator 的任何内容,并且该函数在字符串上返回一对相同类型的容器......

我写了以下,但我没有编译,我尝试将容器类型捕获为 C,并将分配器捕获为 A。

重要的是,我只使用 C++98。

template<template<std::string, A> class C, class A>
static std::pair<T<std::string, A>, T<std::string, A> > Check(const T<std::string, A>::iterator &beg, const T<std::string, A>::iterator &end)
{
    //.... 
}

调用我使用的代码:

vector<string> toCheck; toCheck += "test1", "test2";
pair<vector<string>, vector<string> > found = Check(toCheck.begin(), check.end());

您知道如何编写该函数吗?

【问题讨论】:

    标签: c++ templates c++98 type-deduction


    【解决方案1】:

    模板模板参数只能涉及​​模板参数,不能涉及模板参数。这应该有效:

    template<template<class, class> class C, class A>
    static std::pair<C<std::string, A>, C<std::string, A> > Check(const typename C<std::string, A>::iterator &beg, const typename C<std::string, A>::iterator &end)
    {
        //.... 
    }
    

    正如@Jarod42 在 cmets 中指出的那样,上述签名不允许CA 的类型推断。无论如何它都不符合您的用例;为此,使用它,这将推导出CA 就好了:

    template<template<class, class> class C, class A>
    static std::pair<C<std::string, A>, C<std::string, A> > Check(const C<std::string, A> &container)
    {
        //.... 
    }
    

    【讨论】:

    • 注意这里编译器不能推断类型,用户必须提供CA
    • 但是我们可以用编译器推导出 C 和 A 的方式来实现吗?
    • @alexbuisson 查看编辑。但请注意,没有办法让容器类型的类型推导仅适用于迭代器参数。
    • 使用一些 type_traits 从迭代器中查找 compatible 容器可能会有所帮助。
    • @Jarod42 我现在没有时间添加它;随时提供您自己的答案:-)
    猜你喜欢
    • 1970-01-01
    • 2018-02-19
    • 2012-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-08
    • 1970-01-01
    • 2020-02-17
    相关资源
    最近更新 更多