The program below does not compile if I uncomment the line containing foo<double>()
, because B<double>
depends on A<double>
, which is an incomplete type.
#include <iostream>
using namespace std;
template <class T> struct A; // forward declaration (incomplete)
template <> struct A<int> {}; // specialized for int
template <class T> struct B : A<T> { int foo() {return 0;} }; // derived class, general definition inherits from A
template <> struct B<bool> { int foo() {return 1;} }; // derived class, does not inherit from A
template <class T> int foo() { B<T> b; return b.foo(); } // to be called if B<T> is valid
int main()
{
cout << foo<int>() << "\n"; // print 0
cout << foo<bool>() << "\n"; // print 1
// cout << foo<double>() << "\n"; // this line would generate a compile error
}
I would like a way to overload the function foo
so that if B<T>
is not a valid type, then an alternative version of the function foo
is called.
I.e. I would like to have a way to define the overload
template <class T> int foo() { return -1; } // to be called if B<T> is not valid
I can also wrap the function foo
inside a struct, if that helps. Is there a way to do that in C++03?