To familiarize myself with the C++ compiler in XCode, I've been running through a number of code examples from Scott Meyer's "Effective C++". However, the following code snippet based on Item 25 gives me a 'const class initialization' error or something to this effect. I don't have access to XCode at the moment, but the same snippet on Microsoft Visual C++ .NET compiles and runs with no warnings and, of course, no errors.
Try this:
#include <iostream>
using namespace std;
// Declare an anonymous const class with template
// type-conversion functions. The first one converts
// NULLPTR to any type of null non-member pointer.
// The second achieves the same result for any type
// of null *class member* pointer.
const class
{
public:
template<class T>
operator T*() const { return 0; }
template<typename C, typename T>
operator T C::*() const { return 0; }
private:
// suppress address-of operator because it
// is meaningless to take the address of this
// null pointer
void operator&() const;
} NULLPTR;
// Create a set of overloaded functions to try this out.
// First takes an int, second takes a char*.
void f(int x)
{
cout << "f(int x) has been called\n";
return;
}
void f(char* str)
{
cout << "f(char* str) has been called\n";
return;
}
// main
int main(int argc, char* argv[])
{
f(NULLPTR);
return 0;
}
The expected outcome is, of course, "f(char* str) has been called". Can you get this to compile and run on XCode?
P.S. If keyword "typename" does not work, replace with "class".
Try this:
#include <iostream>
using namespace std;
// Declare an anonymous const class with template
// type-conversion functions. The first one converts
// NULLPTR to any type of null non-member pointer.
// The second achieves the same result for any type
// of null *class member* pointer.
const class
{
public:
template<class T>
operator T*() const { return 0; }
template<typename C, typename T>
operator T C::*() const { return 0; }
private:
// suppress address-of operator because it
// is meaningless to take the address of this
// null pointer
void operator&() const;
} NULLPTR;
// Create a set of overloaded functions to try this out.
// First takes an int, second takes a char*.
void f(int x)
{
cout << "f(int x) has been called\n";
return;
}
void f(char* str)
{
cout << "f(char* str) has been called\n";
return;
}
// main
int main(int argc, char* argv[])
{
f(NULLPTR);
return 0;
}
The expected outcome is, of course, "f(char* str) has been called". Can you get this to compile and run on XCode?
P.S. If keyword "typename" does not work, replace with "class".