c ++函数模板编译错误“'containerType'不是模板” [英] c++ function template compiles error "‘containerType’ is not a template"

查看:316
本文介绍了c ++函数模板编译错误“'containerType'不是模板”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写一个函数stringify参数用于日志目的。例如,我想写如下:

I'm trying to write a function to "stringify" parameters for logging purpose. For example, I'd like to write something like this:

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();
} 

这是我得到的错误信息: 'containerType'不是模板

Here is the error message I got: error: ‘containerType’ is not a template

谢谢,
Alex

Thanks, Alex

推荐答案

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

You need to use a template template parameter, e.g.,

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



如果您希望将其与标准库容器一起使用,则大多数都有多个模板参数(例如,序列容器有两个:一个用于值类型,另一个用于分配器类型)。

Note that if you are expecting to use this with standard library containers, most of them have several template parameters (the sequence containers, for example, have two: one for the value type and one for the allocator type).

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

It is probably easier (and better) to use the value_type typedef that all containers have. For example,

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

这篇关于c ++函数模板编译错误“'containerType'不是模板”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆