1

Consider the following code:

#include <iostream>
#include <vector>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/io.hpp>

int main()
{
    namespace ublas = boost::numeric::ublas;

    double   d = M_PI;
    unsigned u = d;

    std::cout << "d = " << d << std::endl;
    std::cout << "u = " << u << std::endl;

    ublas::bounded_vector<double,3>   dVec = ublas::scalar_vector<double>(3,M_PI);
    ublas::bounded_vector<unsigned,3> uVec = dVec; // type conversion!

    std::cout << "dVec = " << dVec << std::endl;
    std::cout << "uVec = " << uVec << std::endl;

    return 0;
}

When I compile this using g++ (version 4.6.1) with the following options:

g++  -g3 -Wall -Wextra -ansi -pedantic -Wconversion -std=c++0x test.cpp -o test

I get the following warnings:

test.cpp: In function ‘int main()’:
test.cpp:11:22: warning: conversion to ‘unsigned int’ from ‘double’ may alter its value [-Wconversion]

When I run the program I get:

$ ./test
d = 3.14159
u = 3
dVec = [3](3.14159,3.14159,3.14159)
uVec = [3](3,3,3)

The compiler produced a warning for the conversion of the scalars but there was no warning for the ublas conversion, is there a way of having the compiler write a warning in that case? It looks like -Wconversion or any of the other options don't do this.

mkm
  • 673
  • 5
  • 21

1 Answers1

0

Why should any compiler warn on this?

The authors of ublas::bounded_vector<T,N> must have defined a conversion from ublas::bounded_vector<U,N>, otherwise it would not be possible at all. And if there is such function/constructor, there is no reason for the compiler to warn you when you use it.

Sebastian Mach
  • 38,570
  • 8
  • 95
  • 130
  • I had an error in my code caused by exactly this problem. It would be a helpful warning to receive because it is quite a difficult thing to notice, if the compiler had given a warning I would have noticed it straight away. If it's not possible to get a warning message from the compiler is there another way to catch bugs of this type? I'm working with quite a large code so it's not practical to go through all the files individually. – mkm Mar 22 '12 at 14:19
  • @mk527: As said, no compiler in the world can give you a warning at all. For that, it would be required that the compiler looks into your head to see your intentions ;) But apart from that, I think there is no clean C++ solution, except writing a proxy that holds a vector as a private member, and which exposes only what you really need. – Sebastian Mach Mar 22 '12 at 14:51