2017-06-20 165 views
1

有可能通过转让给Eigen::Map转换为Matrix转换的本征:: TensorMap到本征::张量

vector<float> v = { 1, 2, 3, 4 }; 
auto m_map = Eigen::Map<Eigen::Matrix<float, 2, 2, Eigen::RowMajor>>(&v[0]); 
Eigen::MatrixXf m = m_map; 
cout << m << endl; 

这将产生:

1 2 
3 4 

如果我试图做同样的事情与Tensor

vector<float> v = { 1, 2, 3, 4 }; 
auto mapped_t = Eigen::TensorMap<Eigen::Tensor<float, 2, Eigen::RowMajor>>(&v[0], 2, 2); 
Eigen::Tensor<float, 2> t = mapped_t; 

我只是得到编译器错误YOU_MADE_A_PROGRAMMING_MISTAKE。有没有办法将TensorMap转换成张量?

回答

2

那么,Eigen::RowMajor不是Eigen::Tensor的默认值,这意味着您没有指定相同的类型,这意味着YOU_MADE_A_PROGRAMMING_MISTAKE。您必须明确请求交换布局。

#include <vector> 
#include <unsupported/Eigen/CXX11/Tensor> 

int main() 
{ 
    std::vector<float> v = { 1, 2, 3, 4 }; 
    auto mapped_t = Eigen::TensorMap<Eigen::Tensor<float, 2, Eigen::RowMajor>>(&v[0], 2, 2); 
    Eigen::Tensor<float, 2> t = Eigen::TensorLayoutSwapOp<Eigen::Tensor<float, 2, Eigen::RowMajor>>(mapped_t); 
} 

使用C++ 14,你可以为它写一个很好的实例化函数。

#include <type_traits> 
#include <vector> 
#include <unsupported/Eigen/CXX11/Tensor> 

namespace Eigen { 
    template < typename T > 
    decltype(auto) TensorLayoutSwap(T&& t) 
    { 
    return Eigen::TensorLayoutSwapOp<typename std::remove_reference<T>::type>(t); 
    } 
} 

int main() 
{ 
    std::vector<float> v = { 1, 2, 3, 4 }; 
    auto mapped_t = Eigen::TensorMap<Eigen::Tensor<float, 2, Eigen::RowMajor>>(&v[0], 2, 2); 
    Eigen::Tensor<float, 2> t = Eigen::TensorLayoutSwap(mapped_t); 
}