mangoer
mangoer

Reputation: 1

Use of function templates

In my program,T may be of type double or of type Eigen::MatrixXd,so I use is_same<T,double>::value as condition to execute different code blocks。 But the program build faild.The failure description is Binary operator "=" no operator found that accepts a right-hand operand of type double。I know there is a problem with codedata_storage = *((double*)pt_property->data) and codedata_storage(j, i) = *((double*)pt_property->data + pt_offset); ,but i don't know why.
thanks.
Below is my code.

template<typename T>
void MediumModelTest::ReadMatrixData(matvar_t* pt_mat_cp_data, T& data_storage, string property_name)
{
    matvar_t* pt_property = Mat_VarGetStructFieldByName(pt_mat_cp_data, property_name.c_str(), 0);
    ASSERT_NE(pt_property,nullptr);

    if (is_same<T,double>::value)
    {
        data_storage = *((double*)pt_property->data);
    }
    else
    {
        unsigned int rows = pt_property->dims[0];
        unsigned int cols = pt_property->dims[1];
        unsigned int pt_offset = 0;

        data_storage.resize(rows, cols);
        
        for (int i = 0; i < cols; i++)
        {
            for (int j = 0; j < rows; j++)
            {
                data_storage(j, i) = *((double*)pt_property->data + pt_offset);
                pt_offset++;
            }
        }
    }
}

enter image description here

Upvotes: 0

Views: 45

Answers (1)

SoronelHaetir
SoronelHaetir

Reputation: 15172

Change your

if (is_same<T,double>::value)

to

if constexpr(is_same<T,double>::value)

In the plain "if" case the compiler still has to evaluate both branches, the compiler isn't allowed to discard the false branch even though the value is known at compile-time. But with the version you posted only one branch actually makes sense, depending on the type of T.

Upvotes: 1

Related Questions