用于转换 std::vectors 的简单模板函数——“非法使用这种类型作为表达式" [英] Simple templated function to convert std::vectors - "illegal use of this type as an expression"

查看:23
本文介绍了用于转换 std::vectors 的简单模板函数——“非法使用这种类型作为表达式"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个将 std::vectors 从一种类型转换为另一种类型的快速方法:

I wrote a quick method to convert std::vectors from one type to another:

template<class A, class B>
vector<B> ConvertSTDVector_AToB(vector<A> vector)
{
    vector<B> converted_vector;

    for(unsigned int i= 0; i< vector.size(); i++)
        converted_vector.push_back(vector[i]);

    return converted_vector;
}

但编译器在左括号后的行中出现错误 C2275:'B':非法使用此类型作为表达式"的错误.起初我以为在其他地方以某种方式定义了B",但是更改两个模板类型名称会导致相同的错误.然后我认为这些类型发生了一些奇怪的事情.但即使将两个模板参数设为 int 也不会改变任何东西.

But the compiler errors with "error C2275: 'B' : illegal use of this type as an expression" on the line after the opening bracket. At first I thought somehow 'B' was defined elsewhere, but changing both template type names results in the same error. Then I thought that something strange was going on with the types. But even making both template parameters ints doesn't change anything.

我这辈子都看不出这种方法有什么问题.(虽然我觉得在这一点上我可能只是对一些明显的东西视而不见).

I can't for the life of me see what's wrong with this method. (Although I feel like I might just be blind to something obvious, at this point).

推荐答案

只需重命名参数名称即可.它的名称隐藏了 std::vector 名称.

Simply rename the parameter name. Its name hides the std::vector name.

或者按照下面的方式写错行

Or write the erroneous line the following way

class vector<B> converted_vector;

即为 std::vector 使用详细的类型名称,以将其与对象(参数)向量区分开来.

that is use the elaborated type name for std::vector that to distinguish it from object (parameter) vector.

函数的代码可以用不同的方式编写.例如

The code of the function can be written in different ways. For example

template<class A, class B>
vector<B> ConvertSTDVector_AToB(vector<A> vector)
{
    class vector<B> converted_vector( vector.begin(), vector.end() );

    return converted_vector;
}

公关

template<class A, class B>
vector<B> ConvertSTDVector_AToB(vector<A> vector)
{
    class vector<B> converted_vector;

    converted_vector.assign( vector.begin(), vector.end() );
    return converted_vector;
}

等等.

这篇关于用于转换 std::vectors 的简单模板函数——“非法使用这种类型作为表达式"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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