Rodrigo Custodio Rodrigo Custodio -3 years ago 153
C++ Question

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{

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

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?

Answer Source

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_;}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download