我有以下代码使用Eigen C++库.
void myFunc(Eigen::MatrixXf& myrow)
{
myrow.setOnes();
}
int main()
{
Eigen::MatrixXf A(2,3);
Eigen::MatrixXf tmp1(1,3);
myFunc(tmp1);
A.row(1) = tmp1;
std::cout<<"A is..\n"<<A<<std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如您所见,为了操纵Matrix A的行,我使用了临时变量"tmp1".是否可以在不使用任何临时变量的情况下完成?我不想将整个矩阵"A"作为参数传递给函数.请注意,"myFunc"仅仅是一个例子,我可能需要在函数内部做一些复杂的操作来操作"A"行.还请注意,有时我想在示例中给出"myFun".所以我需要一个适用于这两种情况的解决方案.
以下代码编译正常.
#include <iostream>
#include <vector>
using namespace std;
class MyClass
{
public:
MyClass()
{
x.resize(2);
x[0] = 10;
x[1] = 100;
}
std::vector<int> getValue()
{
return x;
}
const std::vector<int>& getValue() const
{
return x;
}
private:
std::vector<int> x;
};
int main()
{
MyClass m;
std::vector<int> y = m.getValue();
for(int i=0; i<y.size(); i++)
{
std::cout<<y[i]<<std::endl;
}
const std::vector<int>& z = m.getValue();
for(int i=0; i<z.size(); i++)
{
std::cout<<z[i]<<std::endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是,当我通过添加"const"(std :: vector getValue()const)将"std :: vector getValue()"更改为更正确的版本(因为该函数应该更改对象)时,它给出以下内容编译错误.
error: 'const …Run Code Online (Sandbox Code Playgroud) 我需要实现一个类,使用模板说'MyClass'.
template<class T>
class MyClass
{
public:
T var1;
T1 var2;
};
Run Code Online (Sandbox Code Playgroud)
有两个成员变量var1和var2.如果类模板参数,"T",是基本的类型(例如:浮动,双或长双),类型两者变量VAR1和VAR2的应该是相同的作为模板的参数.在上面的例子中,这是T1 = T.
但是,如果模板参数是std::complex<T>,我想拥有
T var1;
std::complex<T> var2;
Run Code Online (Sandbox Code Playgroud)
如何在C++ 11中实现它?
c++ templates template-specialization c++11 template-argument-deduction
请考虑以下代码.
#include <iostream>
class A {
public:
using T = float;
A(const T& x)
{
m_value = x;
}
T& value();
private:
T m_value;
};
// A::T& A::value()
// {
// return m_value;
// }
auto& A::value() -> T &
{
return m_value;
}
int main()
{
A a(10.0);
std::cout << a.value() << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
使用C++ 11进行编译时,出现以下错误.
error: ‘value’ function with trailing return type has ‘auto&’ as its type rather than plain ‘auto’
auto& A::value()->T &
^
Run Code Online (Sandbox Code Playgroud)
等效代码(注释函数)工作正常.但是我想使用尾随返回类型.