简体   繁体   中英

Implicit conversion to std::vector

I've trying to make an implicit conversion from a class that wraps a std::vector to std::vector, but I keep getting this error:

error: conversion from 'const value_type {aka const MatrixRow}' to non-scalar type 'std::vector'

My class MatrixRow is defined like this:

template <typename NumericType>
class MatrixRow{
public:

    // a lot of other methods here
    //....
    //......
    explicit operator std::vector<NumericType>() {return row_;}
    //...
    //...

private:
    std::vector<NumericType> row_;
}

The error occurs when I try to make the following in other part of my code:

std::vector<NumericType> row = obj.matrix_[0]; //obj.matrix_[0] is an object of type MatrixRow<NumericType>

It is the first time that I'm using implicit conversions so probably I didn't understood how to use them properly. What I'm doing wrong?

As your operator is explicit , you should use different syntax:

std::vector<NumericType> row(obj.matrix_[0]);

BTW, you may return const reference to avoid copy:

explicit operator const std::vector<NumericType>&() const {return row_;}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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