C ++ Why is the constructor in this example called twice?

I'm just trying to understand the behavior of the following situation:

template <typename T1>
struct A{
    template <typename T2>
    A(T2 val){
        cout<<"sizeof(T1): "<<sizeof(T1)<<" sizeof(T2): "<<sizeof(T2)<<endl;
    }
    T1 dummyField;
};

so the class is templated with T1 and the constructor is templated with T2

now - if I write:

A<bool> a = A<bool>(true);

the output will be as expected:

sizeof(T1): 1 sizeof(T2): 1

however - if I write:

A<bool> a = A<float>(3.5f);

output:

sizeof(T1): 4 sizeof(T2): 4
sizeof(T1): 1 sizeof(T2): 4

why is the constructor called twice with the float template parameter?

thank you for satisfying my curiosity

+5
source share
3 answers

How to avoid copying?

In both cases, two constructors are called, but you do not see them in the first case, since one of them is a generated compiler. If you want to avoid copying, you need to use a different syntax, for example:

A<bool> a(true);

A<bool> a(3.5f);

( ) ?

A<bool> a = A<bool>(true);

A (bool val) , A A. , . : , .

A<bool> a = A<float>(3.5f);

A<float>(float val) , A<bool>( A<float> val) .

+7

A<bool>(A<bool> const&)

,

 template <typename T2>
A(A<T2>const& val){
    cout<<sizeof(val.dummmyField)<<endl;
}

+6

Because you first create a float instance of the template class.

This is A<float>(3.5f)apart.

Then create A<bool>by hiding A<float>before A<bool>. Therefore, the constructor is first called for A<float>-instance. Instance-instance is A<bool>called.

+3
source

All Articles