模板class的成员函数如何传参?
How to pass a parameter by reference to a member function of template class?
我有一个模板 class,其构造函数接受参数作为参考。我正在寻找一种在调用函数中传递变量的方法。
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)
您不能将右值(即 true
)绑定到非常量左值引用(即 bool&
)。例如你不能做 bool& b = true;
.
要解决此问题,您可以将参数类型更改为 T
或 const T&
。
我有一个模板 class,其构造函数接受参数作为参考。我正在寻找一种在调用函数中传递变量的方法。
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)
您不能将右值(即 true
)绑定到非常量左值引用(即 bool&
)。例如你不能做 bool& b = true;
.
要解决此问题,您可以将参数类型更改为 T
或 const T&
。