Thread: Passing parameters between templated functions

  1. #1
    Registered User SpaceCadet's Avatar
    Join Date
    Oct 2006
    Posts
    23

    Question Passing parameters between templated functions

    I am having trouble getting a template function to recognise that it has been passed a reference by a calling template function. This example code demonstrates the problem.

    Code:
    template<typename T>outputData<T data>
    {
        cout<<data<<endl;
    }
    
    template<typename T>displayData<T data>
    {
        outputData(data)
    }
    
    int main()
    {
        string name("Muppet");
        string &reference=name;
    
        displayData(reference);
    }
    The problem is that the failure to recognise that a string reference is passed through the template functions, is causing the string copy constructor to be called. This is hitting performance.

    Do I have to explicitly declare overrides of the template functions that explicity declare reference arguments? I think this will likley yield ambiguity when the compiler tries to resolve which override of a template to use to generate the explicit vrsion of the code to match the arguments passed.
    All questions are easy. The answers cause the problem...

  2. #2
    Registered User Tonto's Avatar
    Join Date
    Jun 2005
    Location
    New York
    Posts
    1,465
    Can you live with making it a const-reference?

    Code:
    class foo
    {
        friend ostream & operator << (ostream & o, const foo & f);
    
    public:
    
        foo() { cout << "foo()" << endl; }
        foo(const foo & o) { cout << "foo(const foo &)" << endl; }
        ~foo() { cout << "~foo()" << endl; }
        foo & operator = (const foo & o) { cout << "operator = ()" << endl; }
    };
    
    template <typename T> 
        void outputData(const T & data)
    {
        cout << data << endl;
    }
    
    template <typename T> 
        void displayData(const T & data)
    {
        outputData(data);
    }
    
    int main()
    {
        foo f;
        displayData(f);
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Passing arguments between functions
    By Wiretron in forum C Programming
    Replies: 4
    Last Post: 05-17-2006, 04:59 PM
  2. Replies: 1
    Last Post: 02-06-2003, 03:33 PM
  3. Passing parameters
    By pdstatha in forum C++ Programming
    Replies: 1
    Last Post: 06-30-2002, 10:07 AM
  4. Passing data/pointers between functions
    By TankCDR in forum C Programming
    Replies: 1
    Last Post: 11-02-2001, 12:59 AM
  5. passing functions with variable
    By itld in forum C++ Programming
    Replies: 1
    Last Post: 10-30-2001, 11:43 PM