Sign in to follow this  
c4c0d3m0n

Help with namespaces

Recommended Posts

range.h
///
/// range.h
///
///


#ifndef RANGE_H
#define RANGE_H



namespace rob
{


template<class T>
struct range
{
public:

    range( const T& lower, const T& higher );

    T lower;
    T higher;

    T delta();
    T mean();

};


} // End of namespace



#endif // RANGE_H

range.cpp
///
/// range.cpp
///
///


#include "range.h"
#include <algorithm>



template<class T>
rob::range<T>::range( const T& lower, const T& higher )
: lower( lower ),
  higher( higher )
{
    if( lower > higher )
      std::swap( lower, higher );
}


template<class T>
T rob::range<T>::delta()
{
    return higher-lower;
}


template<class T>
T rob::range<T>::mean()
{
    return (higher-lower)/2;
}



/// End of range.cpp
///

In my main() function
    rob::range<float> velrange( 200.0, 400.0 );
    rob::range<float> weightrange( 1.0, 2.0 );
Errors:
.objs\main.o:main.cpp:(.text+0x277): undefined reference to `rob::range<float>::range(float const&, float const&)'
.objs\main.o:main.cpp:(.text+0x2af): undefined reference to `rob::range<float>::range(float const&, float const&)'
I'm lost, what am I doing wrong? How come the reference to the rob::range constructor is not defined yet?

Share this post


Link to post
Share on other sites
I don't like using namespace foo;, that's why I always use the foo:: attachment. I don't think that this makes the difference.

Why woud I need the template code in the same file? Please explain. How does std::vector<> use a template if it's not in my same file?

Share this post


Link to post
Share on other sites
If you look at the vector header, you'll note that it has the full class definition in it. Templates must be completely defined at the point they're used; this means that, unless you are confining use to a single .cpp file, you must completely define your templates in their headers or equivalent.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this