Templates exercise problem
I'm trying to make the following exercise from Thinking in C++ Vol 2, witch says:
In the following code the class NonComparable does not have a operator =(). Why would the presence of the class HardLogic cause a compile error but SoftLogic would not ?
#include <iostream>
using namespace std;
class NonComparable {};
struct HardLogic {
NonComparable nc1, nc2;
void compare()
{
return nc1 == nc2;
}
};
template<class T>
struct SoftLogic {
NonComparable nc1, nc2;
void noOp() {}
void compare()
{
nc1 == nc2;
}
};
int main()
{
SoftLogic<NonComparable> l;
l.开发者_StackOverflow社区noOp();
return 0;
}
1) HardLogic::compare returns void but the function tries o return a int/bool.
2) SoftLogic also has something weird(for me): nc1 == nc2. 3) The exercise says about operator =(), but in the code it is using operator ==().Are thoose mistakes? I found it odd to be so many mistakes in a code from a book like this, so am I missing something ? Did anyone encounter this exercise before ?
Because compilers are not required to diagnose templates that can never be instantiated to valid specializations. They are only required to diagnose them when they are actually instantiated. Whether they diagnose them any earlier is only a quality of implementation.
This is true for member functions of class templates too. If you would try to call l.compare()
, the compiler will need to instantiate the member function, and would be required to diagnose the error.
A good compiler would given an error in both cases.
HardLogic::compare returns void but the function tries o return a int/bool
Since the operator==
in question is not defined, you don't know what it would return. It could return void
, in which case return nc1 == nc2;
would be fine.
Are thoose mistakes? I found it odd to be so many mistakes in a code from a book like this, so am I missing something
Check the errata pages of the book, if they exist. From what I can see from your description, it contains at least one typo (operator=
vs operator==
).
HardLogic::compare returns a bool when the return type in prototype is void SoftLogic::compare returns void in prototype and does not return anything, which is perfectly OK
精彩评论