03.12.2012 Views

C++ for Scientists - Technische Universität Dresden

C++ for Scientists - Technische Universität Dresden

C++ for Scientists - Technische Universität Dresden

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

148 CHAPTER 5. META-PROGRAMMING<br />

template <br />

struct enable if<br />

: public enable if c<br />

{};<br />

The real enabling behavior is realized in enable if c whereas enable if is merely a convience function<br />

to avoid type ‘::value’.<br />

Now we have all we need to implement the L1 norm in the generic fashion we aimed <strong>for</strong>:<br />

1 template <br />

2 typename boost::enable if::type<br />

3 inline one norm(const T& A)<br />

4 {<br />

5 using std::abs;<br />

6 typedef typename Magnitude::type mag type;<br />

7 mag type max(0);<br />

8 <strong>for</strong> (unsigned c= 0; c < num cols(A); c++) {<br />

9 mag type sum(0);<br />

10 <strong>for</strong> (unsigned r= 0; r < num cols(A); r++)<br />

11 sum+= abs(A[r][c]);<br />

12 max= max < sum ? sum : max;<br />

13 }<br />

14 return max;<br />

15 }<br />

16<br />

17 template <br />

18 typename boost::enable if::type<br />

19 inline one norm(const T& v)<br />

20 {<br />

21 using std::abs;<br />

22 typedef typename Magnitude::type mag type;<br />

23 mag type sum(0);<br />

24 <strong>for</strong> (unsigned r= 0; r < size(v); r++)<br />

25 sum+= abs(v[r]);<br />

26 return sum;<br />

27 }<br />

The selection is now driven by enable if in line 2 and 18. Let us look at line 2 in detail <strong>for</strong> a<br />

matrix argument:<br />

1. is matrix is evaluated to (i.e. inherited from) true ;<br />

2. enable if passes true ::value i.e. true to enable if c;<br />

3. enable if c< >::type is set to typename Magnitude::type;<br />

4. This is the return type of the function overload.<br />

What happens in this line when the argument is not a matrix type:<br />

1. is matrix is evaluated to (i.e. inherited from) false ;<br />

2. enable if passes false ::value i.e. false to enable if c<br />

3. enable if c< >::type is not set in this case;

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!