简体   繁体   English

如何为STL容器指定模板功能?

[英]How to specify template function for STL container?

I need to write values of different types to a std::wstringstream . 我需要将不同类型的值写入std::wstringstream At one time we need to write one ore more values. 有一段时间我们需要写出一个或多个值。 I have tried to implement it like this: 我试图像这样实现它:

wstringstream _str;     

template<typename ValueType> //(1)
void WriteValue(const ValueType& val)
{
    _str << val;
}

template<typename ValueType> //(2)
void WriteValue(const std::vector<ValueType>& vals)
{
    for (auto it = vals.begin(); it!= vals.end(); ++it)
    {
        WriteValue<ValueType>(*it);
        _str << L" ";            
    }
}

template<typename ValueType>
void WriteRecord(const std::wstring& name, const ValueType & val)
{
     _str << name;
     WriteValue<ValueType>(val);
}

void Foo()
{
    int bar = 0;
    WriteRecord<int>(L"Lorem", bar); //it's okay

    std::vector<int> buz(4, 0);
    WriteRecord<int>(L"ipsum", buz); //it's error
}

I got the following error : 我收到以下错误:

"cannot convert argument 2 from 'std::vector< int, std::allocator < int > >' 
to 'int &'". As seen compiler tries to pass a vector to (1), not (2).

Why so? 为什么这样? Is it possible to make it choose (2) specialized function template? 是否可以选择(2)专门的功能模板?

WriteRecord<int>(L"ipsum", buz);
           ^^^^^

Here you explicitly say that ValueType should be an int . 在这里你明确地说ValueType应该是一个int So the function signature is: 所以函数签名是:

void WriteRecord(const std::wstring& name, const int& val)

And when you try to pass a std::vector as second argument, the compiler can't convert the std::vector to an int . 当您尝试将std::vector作为第二个参数传递时,编译器无法将std::vector转换为int

For functions, there is rarely a need to explicitly name the type of the template argument, you writing the call like this will work: 对于函数,很少需要显式地命名模板参数的类型,您编写这样的调用将起作用:

WriteRecord(L"ipsum", buz); //Compiler deduces ValueType

If you really need to specify the template argument, use decltype : 如果确实需要指定模板参数,请使用decltype

WriteRecord<decltype(buz)>(L"ipsum", buz);

or just write it out (not recommended) 或者只写出来(不推荐)

WriteRecord<std::vector<int>>(L"ipsum", buz);
std::vector<int> buz(4, 0);
WriteRecord<int>(L"ipsum", buz);
//          ^^^

You're telling the compiler ValueType is int but then you're passing vector<int> as the argument. 你告诉编译器ValueTypeint但是你传递vector<int>作为参数。 The compiler is perfectly capable of deducing template argument types, so stop specifying them everywhere unnecessarily. 编译器完全能够推导出模板参数类型,因此请不必要地在任何地方停止指定它们。 Your Foo function should look like this: 你的Foo函数应如下所示:

void Foo()
{
    int bar = 0;
    WriteRecord(L"Lorem", bar);

    std::vector<int> buz(4, 0);
    WriteRecord(L"ipsum", buz);
}

Similarly, remove the explicitly specified template arguments in the calls to WriteValue in the other functions. 同样,在其他函数的WriteValue调用中删除显式指定的模板参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM