I'm looking to use some c++11 features in some existing c++ projects, so I started changing compile flags in Clang for some projects, and I keep running into a specific issue regarding C++11's treatment of conversion operators (or cast operators) that I didn't expect to see and don't understand why this is now considered an error when it's been valid C++ code that's not c++11
I've boiled it down to this simple example:
#include <iostream>
#include <vector>
class SerializableFormat
{
public:
size_t i;
};
class A
{
public:
size_t x, y;
A(size_t n) : x(n), y(1) { }
operator const SerializableFormat() const
{
SerializableFormat result;
result.i = x;
if (y)
{
result.i /= y;
}
return result;
}
};
int main(int argc, const char * argv[])
{
std::vector<SerializableFormat> v;
for(size_t i = 0; i < 20; i++)
{
v.push_back(A(i));
}
return 0;
}
- If Clang's compilation flags are set to
-std=c++98
andlibstdc++
, there are no issues and this compiles fine. - If Clang's compilation flags are set to
-std=c++11
andlibc++
, I get the errorNo viable conversion from 'A' to 'value_type' (aka 'SerializableFormat')
Just to make it clear-- in case you're thinking about giving SerializableFormat a constructor just for the class A
:
Since the SerializableFormat
class is more suited for conversion to and from various classes, it makes sense for A
(and other classes that wish to be serializable) to have constructors and conversion operators rather than expect SerializableFormat
to cover every type of class that wants to be serializable, so modifying SerializableFormat
to have a special constructor is not a solution.
Can anyone see what I'm doing wrong here?
-std=c++11
, it still compiles. There is no point in your conversion operator returningconst SerializableFormat
-- just returnSerializableFormat
instead, and it'll also work with clang -- but I don't have an answer as to whether your code is valid. – Colloquiumstruct A { }; struct B { operator const A(); }; void f() { (A(B())); }
gets accepted by GCC in all modes, by clang only in C++03 mode. – Colloquium