views:

88

answers:

2

I get no matching member function error when i try to compile this code on my mingw32 compiler

#include <iostream> 
using std::cout;
template <class T>
class Pattern
{
public:
    Pattern(): element(){

        cout<< "default c-tor";
        }

    Pattern(Pattern &copy): element(copy.element){

        cout<< "copy c-tor";

        }

    Pattern& operator=(Pattern &assgn)
    {
        cout<<" assignment operator";
       element = assgn.element;
       return *this;
    }

    ~Pattern(){

        cout<<"destructor";

        }

private:
     T element;
};

template <class T>
Pattern<T> creator()
{
   cout<< "Testing creator";
   Pattern<T> pat;
   return pat;
}

int main()
{
   Pattern<double> pt1(creator<double>());
   Pattern<double> pt2 = creator<double>();
}

Somebody please tell me how to solve the problem.

+5  A: 

Your copy c-tor and assignment operator [of Pattern class] takes parameters as non-const reference .

creator<double>() generates a temporary(object) and temporaries cannot be bound to non-const references. So you get those errors.

ISO C++03 [8.5.3/5]

Otherwise, the reference shall be to a non-volatile const type (i.e., cv1 shall be const).
[Example:

double& rd2 = 2.0; //error: not an lvalue and reference not const

Try passing the parameters (of copy c-tor and assignment operator) as const references.

Prasoon Saurav
+2  A: 

Change as follows:

Pattern(Pattern const &copy): element(copy.element){ 

RValues (such as those returned by creator function instantiation) can bind only to 'reference to const' in C++03.

BTW, something gives me a feeling that you expected the second line in your main to invoke the assignment operator. This is not correct. This statement despite it's appearances invokes the copy constructor to create pt2.

EDIT 2:

$8.5/14- "The initialization that occurs in the form

T x = a;

as well as in argument passing, function return, throwing an exception (15.1), handling an exception (15.3), and aggregate member initialization (8.5.1) is called copy-initialization."

Chubsdad