【问题标题】:c++ function template compiles error "‘containerType’ is not a template"c++函数模板编译报错“‘containerType’不是模板”
【发布时间】:2010-08-08 23:41:10
【问题描述】:

我正在尝试编写一个函数来“字符串化”参数以用于记录目的。例如,我想写这样的东西:

vector<string> queries; 
set<uint_8> filters;
LOG(INFO) << stringify<vector, string>(queries);
LOG(INFO) << stringify<set, uint_8>(filters);

这是我写的函数模板:

template <typename containerType, typename elemType>
string _stringify(const string name, const containerType<elemType> &elems) {
    ostringstream os;
    os << name << ": [";
    BOOST_FOREACH(elemType elem, elems) {
        os << elem << ",";    
    }
    os << "]";
    return os.str();
} 

这是我收到的错误消息:error: ‘containerType’ is not a template

谢谢, 亚历克斯

【问题讨论】:

    标签: c++ templates generics


    【解决方案1】:

    您需要使用模板模板参数,例如,

    template <template <typename> class containerType, typename elemType>
    string _stringify(const string name, const containerType<elemType>& elems)
    

    请注意,如果您希望将此与标准库容器一起使用,它们中的大多数都有几个模板参数(例如,序列容器有两个:一个用于值类型,一个用于分配器类型)。

    使用所有容器都有的value_type typedef 可能更容易(也更好)。例如,

    template <typename ContainerT> 
    void f(const ContainerT& c)
    {
        typedef typename ContainerT::value_type ElementT;  
        // Use ContainerT and ElementT
    }
    

    【讨论】:

    • 谢谢詹姆斯,这是一个很好的答案。干净多了。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-21
    • 2020-10-13
    • 1970-01-01
    • 2018-03-25
    相关资源
    最近更新 更多