简体   繁体   中英

How to pass a parameter by reference to a member function of template class?

I have a template class with a constructor which accepts parameter as reference. I'm looking for a way to pass the variable in the caller function.

template <typename T>
class Data : public ParentClass
{
    T m_data;
public:
    Data(T & data);
    T data() const;
};

template <typename T>
Data<T>::Data(T & data) : m_data(data)
{}

template <typename T>
T Data<T>::data() const
{
    return m_data;
}

int main()
{
    Data<bool> * d = new Data<bool>(true);
    std::cout << d->data() << std::endl;
}

Error : no instance of constructor "Data::Data[with T=bool]" matches the argument list argument types are: (bool)

You can't bind an rvalue (ie true ) to a non-const lvalue-reference (ie bool& ). For example you can't do bool& b = true; .

To solve the issue you can change the parameter type to T or const T& .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM