Hi, why do the types in my codes not match? And how may I resolve this issue? Is there anyway I could make the types match without touching the main() code? The code below is compilable. Need urgent help. Thanks!
#include <iostream>
template <typename T>
class Vector
{
public:
using type = T;
private:
type _x;
type _y;
};
template<typename T>
class Point
{
public:
using type = T;
Point() {}
private:
};
int main()
{
using expect_type1 = float;
using type1 = typename Vector<expect_type1>;
using actua_type_1 = typename Point<type1>::type;
using expec_type2 = double;
using type2 = typename Vector<expect_type2>;
using actua_type_2 = typename Point<type2>::type;
if ((!std::is_same<actua_type_1, expec_type1>::value) ||
(!std::is_same<actua_type_2, expec_type2>::value))
{
std::cout << "Dependent Types don't match" << std::endl;
}
return 0;
}
}
Hmm, I'm not so sure. This is just my part of my homework and I've been using VS to compile the codes. Is there anyway to make the types match without touching the main() code? Been stuck on this for a while. By right, in my actual code, it isn't supposed to pass the if() condition. I really got no clue. This is just a subset of my code.
Well, first let's break down the code, and just focus on the float part.
expect_type1 is float.
type1 is Vector<float>
actual_type1 is Point<Vector<float>>::type, which is then Vector<float>.
So this is essentially trying to say whether float is the same type as Vector<float>, which is false.
I don't think there's really any logical way to make the condition become true.
...usually such subject matter is not a school assignment, so I'm surprised you're using C++17 features like constexpr and what-not.
Doing the comparison by hand: actual_type1 is Point<type1>::type, which is type1. type1 is Vector<expected_type1>, which is Vector<float>
So actual_type1 is Vector<float>
expected_type1 is float.
Vector<float> is not the same as float, so your types don't match.
Can someone break down what the following code means? Still don't really understand entirely. I understand type alias, but this seems a little peculiar to me. Also if possible, explain how it works in relation to above code in general. Thank you.
It makes type mean the same thing as T::Type, in the current scope.
So, if you're talking about coder777's suggestion, to use that code at line 19 of your OP, it would make Point::type mean the same thing as T::type.
So, if we take your line 29:
Point<type1>::type
is
1 2
// line 28 says type1 is Vector<float>>
Point<Vector<float>>::type
is
1 2
// The edited version of line 19 defines what Point<T>::type is
Vector<float>::type
is
1 2
// Line 7 says Vector<T>::type is T
float
EDIT: It needs to be made clear that coder777's suggestion only works, if you assume that Point<T> will only ever be templated on something that has defined its own T::type. If you did something like:
Point<float>
it would fail to compile, because there's no such thing as float::type.