Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ template and shadow parameter

Tags:

c++

templates

I have one simple question. What is the reason of compilation failure?

template <class T>
class test
{
    T varGoodForNothing;
public:
    test()
    { }
    test(test<T> & tt)
    {
        varGoodForNothing = tt.varGoodForNothing;
    }
    test<T> & operator=(const test<T> & tt)
    {
        if (this == &tt)
            return *this;
        test(tt);
        return *this;
    }
};

Compiler error is:

declaration of test tt shadows a parameter.

like image 715
dev1223 Avatar asked Nov 29 '25 21:11

dev1223


1 Answers

What does the standard say?

The standard says that a declaration of type Type (name) is the same has having used Type name, see the below standard quotation.

[dcl.meaning] / 6

In a declaration T D where D has the form

( D1 )

The type of the contained declarator-id is the same as that of the contained declarator-id in the declaration T D1.

Parentheses do not alter the type of the embedded declarator-id, but they can alter the binding of complex declarators.

With that said you are not calling the copy-constructor of test with an argument named tt, instead the compiler thinks that you are trying to declare a variable of type test with the name tt.


How to get around the problem?

To circumvent the problem of T (D); being interpreted as T d; we will have to wrap T inside parentheses, such as in the below.

(test) (tt);

Note: Even if the code will compile after the proposed change it will not do what you want, nor think, it will.

Instead of calling the copy-constructor of test for the given instance you will declare an anonymous instance of test initialized with the value of tt.

Constructors can only be called from within other constructors (using a member initializer list).

like image 131
Filip Roséen - refp Avatar answered Dec 02 '25 15:12

Filip Roséen - refp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!