| Hi,
|
| I run into error with the following program. Would you please help me?
|
| Best wishes,
| Peng
|
| struct tag1{};
| struct tag2{};
should be:
struct Tag1{};
struct Tag2{};
By convention and to save a programmer from having to pop aspirin for a
living, a capitalized name is reserved for structs and classes. So if
you see Tag1, its a type, while tag1 might be an instance of a Tag1
type.
|
| template <typename T>
| inline void test(tag1){
| }
tag1 here is a type, not an instance... you don't need multiple
definitions of the same template either. The following template can
potentially accept any class.
template< typename T >
void test( T& t ) // pass_by_reference
{
}
or
template< typename T >
void test( const T& t ) // pass_by_const_reference
{
// t is unmodifiable and therefore safe
}
|
| template <typename T>
| inline void test(tag2){
| }
above not needed...
|
| int main(){
| test(tag1);//error with g++-3.4.4
// error because tag1 was a type and test() doesn't exist.
Tag1 tag1; // tag1 is an instance of a Tag1 type.
Tag2 tag2;
test< Tag1 >(tag1); // templated<> with a Tag1 type,
// and tag1 is the object being passed
test< Tag2 >(tag2);
int n;
test< int >(n); // doing it with a primitive integer, and so on...
| }
|
If you really did mean to specialize the test template...then...
template< typename T = Tag1 >
void test( T& t )
{
// do this if T is Tag1
}
template<>
void test<Tag2>( T& t )
{
// do this if T is Tag2
}
int main()
{
Tag1 tag1;
test(tag1); // default T = Tag1
Tag2 tag2;
test<Tag2>(tag2); // you must tell the compiler
}