I play with templates of explicit conversion operators in my project to implement an explicit conversion from a custom type type. The minimal example reproducing my problem is as follows (in C ++ 14 mode):
#include <iostream>
#include <stdexcept>
#include <cmath>
using namespace std;
class A
{
public:
template<typename T> explicit operator T() const
{
cout << "operator T" << endl;
return T();
}
template<typename T> explicit operator const T&() const
{
cout << "operator const T&" << endl;
throw runtime_error("operator const T&");
}
template<typename T> explicit operator T&()
{
cout << "operator T&" << endl;
throw runtime_error("operator T&");
}
};
int main(int, char**)
{
try
{
const A& a = A();
cout << abs(static_cast<double>(a) - 3.14) << endl;
}
catch (const runtime_error&)
{
}
return 0;
}
The problem I am facing is the operator selected for static_cast conversion. With GCC, this is the kind of expected (1) case. Output:
operator T
3.14
But Klang refuses to compile it with the following output:
main.cpp:37:20: error: ambiguous conversion for static_cast from 'const A' to 'double'
cout << std::abs(static_cast<double>(a) - 3.14) << endl;
^~~~~~~~~~~~~~~~~~~~~~
main.cpp:10:32: note: candidate function [with T = double]
template<typename T> explicit operator T() const
^
main.cpp:16:32: note: candidate function [with T = double]
template<typename T> explicit operator const T&() const
^
1 error generated.
Why does Clang consider conversion (2) when it seems to need an additional constructor call in the conversion sequence, while (1) will not? And is it right (and then GCC is wrong) to do this?
aclex