Błąd podczas używania decltype () w C ++ 11 (tworzenie nieprzejrzystego komunikatu o błędzie w gcc 4.7.0)
z następującym kodem (gotowa wersja mojego oryginalnego kodu)
#include <iostream>
#include <cmath>
template <typename> class A; // edit 1 following Mark & Matthieu
template <typename X> class A {
X a;
template <typename> friend class A; // edit 1 following Mark & Matthieu
public:
A(X x) : a(x) {}
X get() const { return a; } // edit 2 to avoid using A<Y>::a
template <typename Y>
auto diff(A<Y> const& y) const
-> decltype(a - y.a) // original code causing error with gcc
-> typename std::common_type<X, Y>::type // alternative following Rook
-> decltype(this->get() - // edit 3 not using A<X>::a
y.get()) // edit 2 not using A<Y>::a
{ return a - y.get(); }
};
template <typename X, typename Y>
inline auto dist(A<X> const& x, A<Y> const& y) -> decltype(std::abs(x.diff(y)))
{ return std::abs(x.diff(y)); }
int main()
{
A<double> x(2.0), y(4.5);
std::cout << " dist(x,y)=" << dist(x,y) << '\n'; // <-- error here
}
Otrzymuję następujący błąd z gcc 4.7.0:
test.cc: W funkcjidecltype (std::abs(x.diff(y))) dist(const A<X>&, const A<Y>&)
[zX = double; Y = double; decltype (std::abs(x.diff(y))) = double
] ”:
test.cc:5:5: błąd:double A<double>::a
jest prywatne
podświetlona linia: błąd: w tym kontekście
Ten komunikat o błędzie nie jest oczywiście bardzo pomocny. Czy w moim kodzie jest błąd? Czy jest to problem z kompilatorem?
EDIT1: deklaracja przyjaciela nie pomogła.
EDIT2: unikanie używaniaA<Y>::a
też nie pomogło.
EDIT3: razem zEDIT2 Wreszcienaprawiłem problem. Thedecltype()
w definicjidist()
wymagadecltype()
dlaA<X>::diff()
, które z kolei używaneA<X>::a
, który jest prywatny w pierwszym kontekście.
EDTI4: Propozycja Rooka użyciatypename std::common_type<X,Y>::type
także działa!
EDIT5: ale zobacz odpowiedź Jonathana Wakely'ego nato pytanie