On Mar 1, 4:18 pm, "newbie" <mitbb...@yahoo.comwrote:
Thanks for helping on this problem
But we haven't done anything yet. ;-)
suppose I have the following class
class MyContent {
vector<MyType1 v1;
vector<MyType2 v2;
}
And I have a templated function
template <class Typefoo(vector<Tpye>& a, int type_code, MyContent&
content) {
if(type_code) {
//insert elements in 'a' into content.v1
for(int i = 0; i < a.size(); i++)
content.v1.push_back(a[i]);
} else {
// insert elements in 'a' into content.v2
for(int i = 0; i < a.size(); i++)
content.v2.push_back(a[i]);
}
}
But the compiler complains unmatched type!! How can I solve it?
The problem is that when the function is instantiated, "a" is
(presumably) either of MyType1 or MyType2. The former cannot be put in
v2 and the latter cannot be put in v1, but clearly you are trying to
do just that. Remember, all of the code in the function must compile,
regardless of what path will actually be taken at run-time.
Try this:
class MyContent
{
vector<MyType1 v1;
vector<MyType2 v2;
public:
void Add( const MyType1& a ) { v1.push_back( a ); }
void Add( const MyType2& a ) { v2.push_back( a ); }
}
template <class Type>
void foo(
const vector<Type>& a,
MyContent& content )
{
//insert elements in 'a' into content.v1
for(int i = 0; i < a.size(); i++)
content.Add( a[i] );
}
Note that type_code is gone. Static and dynamic polymorphism are
intended to replace such "type switch" constructs.
Cheers! --M