﻿ 表达模板和C 11 - 代码日志

#### 表达模板和C 11

``````template<typename T>
std::vector<T> operator+(const std::vector<T>& a, const std::vector<T>& b)
{
std::vector<T> tmp;   // vector-sized temporary
for_each(...);
return tmp;
}
``````

``````d = a + b + c;
``````

``````for(int i=0 ; i < vec_length ; ++i)
d[i] = a[i] + b[i] + c[i];
``````

std :: tuple将数据留到std :: pair<>中。最初我

Vec和“表达式”，以便在这种情况下也能正确处理

around：可索引向量和不可索引结果。这是什么

``````#include<algorithm>
#include<iostream>
#include<vector>
#include<tuple>
#include<utility>
#include<array>

template<typename Target,typename Tuple, int N, bool end>
struct Extractor {
template < typename ... Args >
static Target index(int i,const Tuple& t, Args && ... args)
{
return Extractor<Target, Tuple,  N+1,
std::tuple_size<Tuple>::value == N+1>::
index(i, t , std::forward<Args>(args)..., std::get<N>(t).vec[i] );
}
};

template < typename Target, typename Tuple, int N >
struct Extractor<Target,Tuple,N,true>
{
template < typename ... Args >
static Target index(int i,Tuple const& t,
Args && ... args) {
return Target(std::forward<Args>(args)...); }
};

template < typename ... Vs >
std::tuple<typename std::remove_reference<Vs>::type::type_t...>
extract(int i , const std::tuple<Vs...>& tpl)
{
return Extractor<std::tuple<typename std::remove_reference<Vs>::type::type_t...>,
std::tuple<Vs...>, 0,
std::tuple_size<std::tuple<Vs...> >::value == 0>::index(i,tpl);
}

struct Vec {
std::array<int,5> vec;
typedef int type_t;

template<typename... OPs,typename... VALs>
Vec& operator=(const std::pair< std::tuple<VALs...> , std::tuple<OPs...> >& e) {
for( int i = 0 ; i < vec.size() ; ++i ) {
vec[i] = eval( extract(i,e.first) , e.second );
}
}
};

template<int OpPos,int ValPos, bool end>
struct StackMachine {
template<typename... OPs,typename... VALs>
static void eval_pos( std::tuple<VALs...>& vals , const std::tuple<OPs...> & ops )
{
std::get<ValPos+1>( vals ) =
std::get<OpPos>(ops).apply( std::get<ValPos>( vals ) ,
std::get<ValPos+1>( vals ) );
StackMachine<OpPos+1,ValPos+1,sizeof...(OPs) == OpPos+1>::eval_pos(vals,ops);
}
};

template<int OpPos,int ValPos>
struct StackMachine<OpPos,ValPos,true> {
template<typename... OPs,typename... VALs>
static void eval_pos( std::tuple<VALs...>& vals ,
const std::tuple<OPs...> & ops )
{}
};

template<typename... OPs,typename... VALs>
int eval( const std::tuple<VALs...>& vals , const std::tuple<OPs...> & ops )
{
StackMachine<0,0,false>::eval_pos(const_cast<std::tuple<VALs...>&>(vals),ops);
return std::get<sizeof...(OPs)>(vals);
}

struct OpMul {
static int apply(const int& lhs,const int& rhs)  {
return lhs*rhs;
}
};

std::pair< std::tuple< const Vec&, const Vec& > , std::tuple<OpMul> >
operator*(const Vec& lhs,const Vec& rhs)
{
return std::make_pair( std::tuple< const Vec&, const Vec& >( lhs , rhs ) ,
std::tuple<OpMul>( OpMul() ) );
}

template<typename... OPs,typename... VALs>
std::pair< std::tuple< const Vec&, VALs... > , std::tuple<OPs...,OpMul> >
operator*(const Vec& lhs,const std::pair< std::tuple< VALs... > , std::tuple<OPs...> >& rhs)
{
return std::make_pair( std::tuple_cat( rhs.first , std::tuple< const Vec& >(lhs)  ) ,
std::tuple_cat( rhs.second , std::tuple<OpMul>( OpMul() )  ) );
}

template<typename... OPs,typename... VALs>
std::pair< std::tuple< const Vec&, VALs... > , std::tuple<OPs...,OpMul> >
operator*(const std::pair< std::tuple< VALs... > , std::tuple<OPs...> >& lhs,
const Vec& rhs)
{
return std::make_pair( std::tuple_cat( lhs.first , std::tuple< const Vec& >(rhs)  ) ,
std::tuple_cat( lhs.second , std::tuple<OpMul>( OpMul() ) ) );
}

int main()
{
Vec d,c,b,a;

for( int i = 0 ; i < d.vec.size() ; ++i ) {
a.vec[i] = 10+i;
b.vec[i] = 20+i;
c.vec[i] = 30+i;
d.vec[i] = 0;
}

d = a * b * c * a;

for( int i = 0 ; i < d.vec.size() ; ++i )
std::cout << d.vec[i] << std::endl;
}
``````

``````imull   %esi, %edx
imull   32(%rsp), %edx
imull   %edx, %esi
movl    68(%rsp), %edx
imull   %ecx, %edx
movl    %esi, (%rsp)
imull   36(%rsp), %edx
imull   %ecx, %edx
movl    104(%rsp), %ecx
movl    %edx, 4(%rsp)
movl    72(%rsp), %edx
imull   %ecx, %edx
imull   40(%rsp), %edx
imull   %ecx, %edx
movl    108(%rsp), %ecx
movl    %edx, 8(%rsp)
movl    76(%rsp), %edx
imull   %ecx, %edx
imull   44(%rsp), %edx
imull   %ecx, %edx
movl    112(%rsp), %ecx
movl    %edx, 12(%rsp)
movl    80(%rsp), %edx
imull   %ecx, %edx
imull   %eax, %edx
imull   %ecx, %edx
movl    %edx, 16(%rsp)
``````

I was wondering whether lambdas together with move semantics or any other new feature can do as good as ETs. Any thoughts?

ET通常返回代理对象以推迟评估直到后来，因此在触发计算的代码之前没有C 11语言特征的直接明显的益处。也就是说，人们不想写ET代码，但是，在代理建立表达式树的过程中触发运行时代码生成。很好，C 11的移动语义和完美的转发可以帮助避免这种开销，否则应该发生。 (这不可能在C 03.)

``````{
cout << "CASE 1:\n";
math_vector<3> a{1.0, 1.1, 1.2};
math_vector<3> b{2.0, 2.1, 2.2};
math_vector<3> c{3.0, 3.1, 3.2};
math_vector<3> d{4.0, 4.1, 4.2};
math_vector<3> result = a + b + c + d;
cout << '[' << &result << "]: " << result << "\n";
}
``````

``````CASE 1:
0x7fff8d6edf50: math_vector(initlist)
0x7fff8d6edef0: math_vector(initlist)
0x7fff8d6ede90: math_vector(initlist)
0x7fff8d6ede30: math_vector(initlist)
0x7fff8d6edd70: math_vector(copy: 0x7fff8d6edf50)
0x7fff8d6edda0: math_vector(move: 0x7fff8d6edd70)
0x7fff8d6eddd0: math_vector(move: 0x7fff8d6edda0)
0x7fff8d6edda0: ~math_vector()
0x7fff8d6edd70: ~math_vector()
[0x7fff8d6eddd0]: (10,10.4,10.8)
0x7fff8d6eddd0: ~math_vector()
0x7fff8d6ede30: ~math_vector()
0x7fff8d6ede90: ~math_vector()
0x7fff8d6edef0: ~math_vector()
0x7fff8d6edf50: ~math_vector()
``````

``````{
cout << "CASE 2:\n";
math_vector<3> result =
math_vector<3>{1.0, 1.1, 1.2} +
math_vector<3>{2.0, 2.1, 2.2} +
math_vector<3>{3.0, 3.1, 3.2} +
math_vector<3>{4.0, 4.1, 4.2}
;
cout << '[' << &result << "]: " << result << "\n";
}
``````

``````CASE 2:
0x7fff8d6edcb0: math_vector(initlist)
0x7fff8d6edc50: math_vector(initlist)
0x7fff8d6edce0: math_vector(move: 0x7fff8d6edcb0)
0x7fff8d6edbf0: math_vector(initlist)
0x7fff8d6edd10: math_vector(move: 0x7fff8d6edce0)
0x7fff8d6edb90: math_vector(initlist)
0x7fff8d6edd40: math_vector(move: 0x7fff8d6edd10)
0x7fff8d6edb90: ~math_vector()
0x7fff8d6edd10: ~math_vector()
0x7fff8d6edbf0: ~math_vector()
0x7fff8d6edce0: ~math_vector()
0x7fff8d6edc50: ~math_vector()
0x7fff8d6edcb0: ~math_vector()
[0x7fff8d6edd40]: (10,10.4,10.8)
0x7fff8d6edd40: ~math_vector()
``````

> a math_vector_expr< LeftExpr，BinaryOp，RightExpr>类被创建为保存未计算的表达式，
>创建了一个代理plus_op类来保存添加操作，
>将一个构造函数添加到math_vector以接受一个math_vector_expr对象，
>“starter”成员函数以触发表达式模板的创建。

``````CASE 1:
0x7fffe7180c60: math_vector(initlist)
0x7fffe7180c90: math_vector(initlist)
0x7fffe7180cc0: math_vector(initlist)
0x7fffe7180cf0: math_vector(initlist)
0x7fffe7180d20: math_vector(expr: 0x7fffe7180d90)
[0x7fffe7180d20]: (10,10.4,10.8)
0x7fffe7180d20: ~math_vector()
0x7fffe7180cf0: ~math_vector()
0x7fffe7180cc0: ~math_vector()
0x7fffe7180c90: ~math_vector()
0x7fffe7180c60: ~math_vector()

CASE 2:
0x7fffe7180dd0: math_vector(initlist)
0x7fffe7180e20: math_vector(initlist)
0x7fffe7180e70: math_vector(initlist)
0x7fffe7180eb0: math_vector(initlist)
0x7fffe7180d20: math_vector(expr: 0x7fffe7180dc0)
0x7fffe7180eb0: ~math_vector()
0x7fffe7180e70: ~math_vector()
0x7fffe7180e20: ~math_vector()
0x7fffe7180dd0: ~math_vector()
[0x7fffe7180d20]: (10,10.4,10.8)
0x7fffe7180d20: ~math_vector()
``````

``````fldt    128(%rsp)
leaq    128(%rsp), %rdi
leaq    80(%rsp), %rbp
fldt    176(%rsp)
faddp   %st, %st(1)
fldt    224(%rsp)
faddp   %st, %st(1)
fldt    272(%rsp)
faddp   %st, %st(1)
fstpt   80(%rsp)
fldt    144(%rsp)
fldt    192(%rsp)
faddp   %st, %st(1)
fldt    240(%rsp)
faddp   %st, %st(1)
fldt    288(%rsp)
faddp   %st, %st(1)
fstpt   96(%rsp)
fldt    160(%rsp)
fldt    208(%rsp)
faddp   %st, %st(1)
fldt    256(%rsp)
faddp   %st, %st(1)
fldt    304(%rsp)
faddp   %st, %st(1)
fstpt   112(%rsp)
``````

C 11代码实现如下。只需#define DONT_USE_EXPR_TEMPL不使用ET，或根本不定义ET使用ET。

``````#include <array>
#include <algorithm>
#include <initializer_list>
#include <type_traits>
#include <iostream>

//#define DONT_USE_EXPR_TEMPL

//===========================================================================

template <std::size_t N> class math_vector;

template <
typename LeftExpr,
typename BinaryOp,
typename RightExpr
>
class math_vector_expr
{
public:
math_vector_expr() = delete;

math_vector_expr(LeftExpr l, RightExpr r) :
l_(std::forward<LeftExpr>(l)),
r_(std::forward<RightExpr>(r))
{
}

// Prohibit copying...
math_vector_expr(math_vector_expr const&) = delete;
math_vector_expr& operator =(math_vector_expr const&) = delete;

// Allow moves...
math_vector_expr(math_vector_expr&&) = default;
math_vector_expr& operator =(math_vector_expr&&) = default;

template <typename RE>
auto operator +(RE&& re) const ->
math_vector_expr<
math_vector_expr<LeftExpr,BinaryOp,RightExpr> const&,
BinaryOp,
decltype(std::forward<RE>(re))
>
{
return
math_vector_expr<
math_vector_expr<LeftExpr,BinaryOp,RightExpr> const&,
BinaryOp,
decltype(std::forward<RE>(re))
>(*this, std::forward<RE>(re))
;
}

auto le() ->
typename std::add_lvalue_reference<LeftExpr>::type
{ return l_; }

auto le() const ->
typename std::add_lvalue_reference<
typename std::add_const<LeftExpr>::type
>::type
{ return l_; }

auto re() ->
typename std::add_lvalue_reference<RightExpr>::type
{ return r_; }

auto re() const ->
typename std::add_lvalue_reference<
typename std::add_const<RightExpr>::type
>::type
{ return r_; }

auto operator [](std::size_t index) const ->
decltype(
BinaryOp::apply(this->le()[index], this->re()[index])
)
{
return BinaryOp::apply(le()[index], re()[index]);
}

private:
LeftExpr l_;
RightExpr r_;
};

//===========================================================================

template <typename T>
struct plus_op
{
static T apply(T const& a, T const& b)
{
return a + b;
}

static T apply(T&& a, T const& b)
{
a += b;
return std::move(a);
}

static T apply(T const& a, T&& b)
{
b += a;
return std::move(b);
}

static T apply(T&& a, T&& b)
{
a += b;
return std::move(a);
}
};

//===========================================================================

template <std::size_t N>
class math_vector
{
using impl_type = std::array<long double, N>;

public:
math_vector()
{
using namespace std;
fill(begin(v_), end(v_), impl_type{});
std::cout << this << ": math_vector()" << endl;
}

math_vector(math_vector const& mv) noexcept
{
using namespace std;
copy(begin(mv.v_), end(mv.v_), begin(v_));
std::cout << this << ": math_vector(copy: " << &mv << ")" << endl;
}

math_vector(math_vector&& mv) noexcept
{
using namespace std;
move(begin(mv.v_), end(mv.v_), begin(v_));
std::cout << this << ": math_vector(move: " << &mv << ")" << endl;
}

math_vector(std::initializer_list<typename impl_type::value_type> l)
{
using namespace std;
copy(begin(l), end(l), begin(v_));
std::cout << this << ": math_vector(initlist)" << endl;
}

math_vector& operator =(math_vector const& mv) noexcept
{
using namespace std;
copy(begin(mv.v_), end(mv.v_), begin(v_));
std::cout << this << ": math_vector op =(copy: " << &mv << ")" << endl;
return *this;
}

math_vector& operator =(math_vector&& mv) noexcept
{
using namespace std;
move(begin(mv.v_), end(mv.v_), begin(v_));
std::cout << this << ": math_vector op =(move: " << &mv << ")" << endl;
return *this;
}

~math_vector()
{
using namespace std;
std::cout << this << ": ~math_vector()" << endl;
}

void swap(math_vector& mv)
{
using namespace std;
for (std::size_t i = 0; i<N; ++i)
swap(v_[i], mv[i]);
}

auto operator [](std::size_t index) const
-> typename impl_type::value_type const&
{
return v_[index];
}

auto operator [](std::size_t index)
-> typename impl_type::value_type&
{
return v_[index];
}

math_vector& operator +=(math_vector const& b)
{
for (std::size_t i = 0; i<N; ++i)
v_[i] += b[i];
return *this;
}

#ifndef DONT_USE_EXPR_TEMPL

template <typename LE, typename Op, typename RE>
math_vector(math_vector_expr<LE,Op,RE>&& mve)
{
for (std::size_t i = 0; i < N; ++i)
v_[i] = mve[i];
std::cout << this << ": math_vector(expr: " << &mve << ")" << std::endl;
}

template <typename RightExpr>
math_vector& operator =(RightExpr&& re)
{
for (std::size_t i = 0; i<N; ++i)
v_[i] = re[i];
return *this;
}

template <typename RightExpr>
math_vector& operator +=(RightExpr&& re)
{
for (std::size_t i = 0; i<N; ++i)
v_[i] += re[i];
return *this;
}

template <typename RightExpr>
auto operator +(RightExpr&& re) const ->
math_vector_expr<
math_vector const&,
plus_op<typename impl_type::value_type>,
decltype(std::forward<RightExpr>(re))
>
{
return
math_vector_expr<
math_vector const&,
plus_op<typename impl_type::value_type>,
decltype(std::forward<RightExpr>(re))
>(
*this,
std::forward<RightExpr>(re)
)
;
}

#endif // #ifndef DONT_USE_EXPR_TEMPL

private:
impl_type v_;
};

//===========================================================================

template <std::size_t N>
inline void swap(math_vector<N>& a, math_vector<N>& b)
{
a.swap(b);
}

//===========================================================================

#ifdef DONT_USE_EXPR_TEMPL

template <std::size_t N>
inline math_vector<N> operator +(
math_vector<N> const& a,
math_vector<N> const& b
)
{
math_vector<N> retval(a);
retval += b;
return retval;
}

template <std::size_t N>
inline math_vector<N> operator +(
math_vector<N>&& a,
math_vector<N> const& b
)
{
a += b;
return std::move(a);
}

template <std::size_t N>
inline math_vector<N> operator +(
math_vector<N> const& a,
math_vector<N>&& b
)
{
b += a;
return std::move(b);
}

template <std::size_t N>
inline math_vector<N> operator +(
math_vector<N>&& a,
math_vector<N>&& b
)
{
a += std::move(b);
return std::move(a);
}

#endif // #ifdef DONT_USE_EXPR_TEMPL

//===========================================================================

template <std::size_t N>
std::ostream& operator <<(std::ostream& os, math_vector<N> const& mv)
{
os << '(';
for (std::size_t i = 0; i < N; ++i)
os << mv[i] << ((i+1 != N) ? ',' : ')');
return os;
}

//===========================================================================

int main()
{
using namespace std;

try
{
{
cout << "CASE 1:\n";
math_vector<3> a{1.0, 1.1, 1.2};
math_vector<3> b{2.0, 2.1, 2.2};
math_vector<3> c{3.0, 3.1, 3.2};
math_vector<3> d{4.0, 4.1, 4.2};
math_vector<3> result = a + b + c + d;
cout << '[' << &result << "]: " << result << "\n";
}
cout << endl;
{
cout << "CASE 2:\n";
math_vector<3> result =
math_vector<3>{1.0, 1.1, 1.2} +
math_vector<3>{2.0, 2.1, 2.2} +
math_vector<3>{3.0, 3.1, 3.2} +
math_vector<3>{4.0, 4.1, 4.2}
;
cout << '[' << &result << "]: " << result << "\n";
}
}
catch (...)
{
return 1;
}
}

//===========================================================================
``````
http://stackoverflow.com/questions/11809052/expression-templates-and-c11