0%

從Boost Variant談起

1
2
3
#include <boost/variant.hpp>
boost::variant<int, std::string> v;
v = "Hello World!";

boost::get

使用boost::get需要給出正確型別,不然會拋出 Exception

1
2
std::cout << boost::get<std::string>(v) << std::endl; // Hello World!
std::cout << boost::get<int>(v) << std::endl; // terminate called after throwing an instance of 'boost::bad_get'

Use RTTI

1
2
3
4
5
6
7
8
void var_print(const boost::variant<int, std::string> &v)
{
if (v.type() == typeid(int)) {
std::cout << boost::get<int>(v) << std::endl;
} else if (v.type() == typeid(std::string)) {
std::cout << boost::get<std::string>(v) << std::endl;
}
}

每增加一種型別就要修改程式碼,並且影響性能

Visitor Pattern

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class var_visitor : public boost::static_visitor<void>
{
public:
void operator()(int i) const {
std::cout << i << std::endl;
}
void operator()(const std::string& str) const {
std::cout << str << std::endl;
}
// the default case:
template <typename T> void operator()(T const &) const {
std::cout << "FALLBACK: " << __PRETTY_FUNCTION__ << "\n";
}
};
boost::apply_visitor(var_visitor(), v);

不過C++17的visit功能更強,實現更優雅

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class var_visitor
{
public
void operator()(int i) const {
std::cout << i << std::endl;
}
void operator()(const std::string& str) const {
std::cout << str << std::endl;
}
// the default case:
template <typename T> void operator()(T const &) const {
std::cout << "FALLBACK: " << __PRETTY_FUNCTION__ << "\n";
}
};
visit(var_visitor(), v);

智逾期他的visit方式就先打住,有空在研究,介紹variant可以作些什麼

Stack-based run-time polymorphism

傳統基於heap based的polymorphism都是這麼做的
– 分配一塊記憶體
– 將物件創造於記憶體上
– 根據vtbl呼叫virtual function
– 歸還記憶體

所以一般都會寫出這樣的程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
struct Base {
virtual ~Base() = default;
virtual void func() const = 0;
};
struct Der1 : public Base {
void func() const override { cout << "Der1" << endl; }
};
struct Der2 : public Base {
void func() const override { cout << "Der2" << endl; }
};

unique_ptr<Base> create(int v)
{
if (v)
return make_unique<Der1>();
else
return make_unique<Der2>();
}

auto test = [](const Base &obj) {
obj.func();
};
auto obj = create(0);
test(*obj);

而基於stack的作法,省去了最前面跟最後面的步驟,因此速度更快,如果有機會devirtualize的話,連vtbl都可以不需要

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using derv = variant<Der1, Der2>;
erv create(int v)
{
if (v)
return Der1();
else
return Der2();
}

template <typename BaseType, typename ... Types>
BaseType& cast_to_base(variant<Types ...>& v)
{
return visit([](BaseType& arg) -> BaseType& { return arg; }, v);
}

auto test = [](const Base &obj) {
obj.func();
};
derv obj = create(0);
test(cast_to_base<Base>(obj));

Reference

variant in C++14
浅谈boost.variant的几种访问方式
让boost.variant支持lambda表达式访问
default visitor function for boost::variant
visiting variants using lambdas - part 1
visiting variants using lambdas - part 2
Polymorphism Polymorphism

不得不說,這真的是個炫技,不過還真有用。
原先的程式碼,煩譟又容易錯

1
2
if (thing.x == 1 || thing.x == 2 || thing.x == 3)
dosomething();

可以改寫成這樣
C++11版

1
2
3
4
5
6
7
8
9
template<typename U, typename ... T>
bool one_of(U&& u, T && ... t)
{
bool match = false;
(void)std::initializer_list<bool>{ (match = match || u == t)... };
return match;
}
if (one_of(thing.x, 1, 2, 3))
dosomething();

關劍在Varadic Template Pack expansion,他創造了一個initial_list,其值就是當下match的值。
將initial_list的值印出來更容易看出變化,因此小小變化一下

1
2
3
4
5
6
7
8
9
template<typename U, typename ... T>
bool one_of(U&& u, T && ... t)
{
bool match = false;
auto list = std::initializer_list<bool>{ (match = match || u == t)... };
for (auto v : list)
std::cout << v << std::endl;
return match;
}

部過我們的inital_list根本沒用到, 所以就直接宣告成void讓編譯氣決定最佳化了
C++17版可以寫得更簡單

1
2
3
4
5
template<typename U, typename ... T>
bool one_of(U&& u, T && ... t)
{
return ( (u == t) || ... );
}

Reference

Parameter pack
C++17 Fold Expressions
A Data Point for MSVC vs Clang Code Generation

Problem

目前的主流就是以composition代替inheritance,因此可以寫出這樣的程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
struct SubCompoent1 {
int v = 100;
int add(int num) { return v + num; }
int sub(int num) { return v - num; }
};
struct SubCompoent2 {
int v = 300;
int mul(int num) { return v * num; }
int div(int num) { return v / num; }
};
struct Component {
Component() : comp1(new SubCompoent1), comp2(new SubCompoent2) {}
std::unique_ptr<SubCompoent1> comp1;
std::unique_ptr<SubCompoent2> comp2;
int add(int num) { return comp1->add(num); }
int sub(int num) { return comp1->sub(num); }
int mul(int num) { return comp2->mul(num); }
int div(int num) { return comp2->div(num); }
};
int func(Component *comp)
{
return comp->add(300);
}
int func1(Component *comp)
{
return comp->div(5);
}

這樣的程式碼很值觀,>不過問題也很明顯,一旦新增一個Function Call,接著又要改個地方

Possible Solution 1

將SubCompent的介面公開,然後提供一組介面存取SubComponent

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
struct Component {
Component() : comp1(new SubCompoent1), comp2(new SubCompoent2) {}
std::unique_ptr<SubCompoent1> comp1;
std::unique_ptr<SubCompoent2> comp2;
SubCompoent1* getComp1() { return comp1.get(); }
const std::unique_ptr<SubCompoent2>& getComp2() { return comp2; }
};
nt func(Component *comp)
{
SubCompoent1* comp1 = comp->getComp1();
return comp1->add(300);
}
int func1(Component *comp)
{
const auto& comp2 = comp->getComp2();
return comp2->div(5);
}

跟上面方式相比,少了每次新增API介面就要修改Component的煩惱,不過要為每組Subcomponent提供一組Access Function,試著將他自動化

Possible Solution 2

結合C++14的get和tuple之後,可以寫成這樣

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct Component {
Component() : comp1(new SubCompoent1), comp2(new SubCompoent2) {}
std::unique_ptr<SubCompoent1> comp1;
std::unique_ptr<SubCompoent2> comp2;
SubCompoent1* getComp1() { return comp1.get(); }
const std::unique_ptr<SubCompoent2>& getComp2() { return comp2; }
};
int func(Component *comp)
{
return comp->get<SubCompoent1>()->add(300);
}
int func1(Component *comp)
{
return comp->get<SubCompoent2>()->div(5);
}

不過這樣還是需要輸出SubComponent的介面,在某些場合底下還是不太適用
不知道未來可不可以靠refelection和overload operator-> 來寫出更好的程式碼

在剛落幕的CppCon的投影片中看到這個tTrick,順手就記下來。果然C/C++是越學越不會的語言啊。

1
2
3
4
5
6
7
8
template<typename T>
void foo(T x)
{
puts(__PRETTY_FUNCTION__); // MSVC: __FUNCSIG__
}
foo(4);
foo(4.2);
foo("hello");

如果是VC的話記得使用__FUNCSIG__
最大的用途是幫忙Debug Template Function…

Transducer原先是在Clojure 1.7被提出的新觀念,由於覺得這觀念實在很有趣。看了幾篇文章之後,打算寫些東西。試著一步一步前進,加深自己印象。

What is Transducer

Transducer 是遊 Transfromreducer 兩個字合成出來的,而
– Transform: 轉換,由 A 變成 B
– Reducer: 接受輸入和先前的狀態,產生一個新的狀態

從一個簡單範例開始

1
2
3
4
5
6
7
8
9
vector<int> calc(const vector<int> &vec)
{
vector<int> result;
for (const auto &v : vec) {
if (v % 2 == 0)
result.push_back(v / 2);
}
return result;
}

這段程式很簡單就知道他在做什麼了,不過他還是有一些圈點
例如新增了一個條件, 不能修改原有條件。
只能寫個95%相像的程式,例如

1
2
3
4
5
6
7
8
9
vector<int> calc2(const vector<int> &vec)
{
vector<int> result;
for (const auto &v : vec) {
if (v > 5)
result.push_back(v * v);
}
return result;
}

雖然一樣能夠解決問題,不過寫久了也是會覺得枯燥乏味。
這邊就缺少了Functional programming中的composability
接著用Functional Progrmaming的觀點來看這問題

來點Functional Programming

先來個C++版的MapFilter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
template <template <typename...> class C, typename T, typename ...TArgs,  typename Fn>
auto Map(Fn fn, const C<T, TArgs...> &container) {
C<T, TArgs...> result;
for (const auto &item : container)
result.push_back(fn(item));
return result;
}
template <typename In, typename Out, typename Pred>
Out filter(In first, In last, Out out, Pred pred) {
for (; first != last; ++first)
if (pred(*first))
*out++ = *first;
return out;
}

重新構建我們的函數

1
2
3
4
5
6
vector<int> calc(const vector<int> &vec)
{
auto div2 = [](auto v) { return v / 2; };
auto isEven = [](auto v) { return v % 2 == 0; };
return Map(div2, Filter(isEven, vec));
}

這下子可以用組合來看這個問題了,不過這方法的問題也顯而易見。仙不論C++中間產物的影響

  • 原先的Solution只要一次Lopp就結束了
  • 這方法需要兩次Loop,一次Filter,一次Map
    這就是改造的地方,因此Reducer上場了

    Reduce

    1
    2
    3
    4
    5
    6
    7
    template <template <typename...> class C, typename T, typename ...TArgs,
    typename S, typename Rf>
    auto reduce(const C<T, TArgs...> &container, S state, Rf step) {
    for (const auto &c : container)
    state = step(state, c);
    return state;
    }
    這個救跟std::accumulate作法差不多。
    加上一個helper function
    1
    2
    3
    4
    auto concat = [](auto result, auto input) {
    result.push_back(input);
    return result;
    };
    上面的Map跟Filter能用Reduce重新實作了
    Map部分
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    auto mapping = [](auto fn) {
    return [=](auto step) {
    return [=](auto s, auto ...ins) {
    return step(s, fn(ins...));
    };
    };
    };
    template <template <typename...> class C, typename T, typename ...TArgs, typename Fn>
    auto Map(Fn fn, const C<T, TArgs...> &container) {
    using retType = C<T, TArgs...>;

    return reduce(container, retType(), mapping(fn)(concat));
    }
    Filter部分
    1
    2
    3
    4
    5
    6
    7
    auto filtering = [](auto pred) {
    return [=](auto step) {
    return [=](auto s, auto ...ins) {
    return pred(ins...) ? step(s, ins...) : s;
    };
    };
    };
    Compose
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    auto compose = [](auto f) {
    return [=](auto g) {
    return [=](auto ...ins) {
    return f(g(ins...));
    };
    };
    };
    template <template <typename...> class C, typename T, typename ...TArgs, typename Pred>
    auto Filter(Pred pred, const C<T, TArgs...> &container) {
    using retType = C<T, TArgs...>;
    return reduce(container, retType(), filtering(pred)(concat));
    }
    我們可以甩開 Map 跟 Filter, 重新打造函數,這下只用到 Reduce,太神奇了
    1
    2
    3
    4
    5
    6
    vector<int> calc(const vector<int> &vec)
    {
    auto div2 = [](auto v) { return v / 2; };
    auto isEven = [](auto v) { return v % 2 == 0; };
    return reduce(vec, vector<int>(), filtering(isEven)(mapping(div2)(concat)));
    }
    加上Compose的話,威力就更大了

    Compose

    定義一個簡單的Compose實作
    1
    2
    3
    4
    5
    auto compose = [](auto f, auto g) {
    return [=](auto x) {
    return f(g(x));
    };
    };
    重新實作我們的 calc function
    1
    2
    3
    4
    5
    6
    7
    vector<int> calc(const vector<int> &vec)
    {
    auto div2 = [](auto v) { return v / 2; };
    auto isEven = [](auto v) { return v % 2 == 0; };
    auto comp = compose(filtering(isEven), mapping(div2));
    return reduce(vec, vector<int>(), comp(concat));
    }
    一切就是這麼神奇

Reference

CSP and transducers in JavaScript
Transducers From Clojure to C++
transducers in C++ 14

Build GCC

怕忘記,寫下來好了。先下載GCC 4.9的Source code且解壓縮。

1
2
3
4
5
6
$ cd gcc-6.1.0
$ ./contrib/download_prerequisites ## 下載GMP, MPFR跟MPC等Library在當前目錄
$ mkdir build && cd build
$ ../configure --enable-checking=release --enable-languages=c,c++ --disable-multilib
$ make -j 4
$ sudo make install

在下configure的時候可以加參數,可以參考這裡
在Debian體系下,利用update-alternatives來替換掉/usr/bin的gcc symbol link

1
$ update-alternatives --install /usr/bin/gcc gcc /usr/local/bin/x86_64-unknown-linux-gnu-gcc-6.1.0 40

關於update-alternatives的用法可參考這裡

Reference build

為了工作上的需要,試著把FFMpeg放入Browser中,雖然成功了,但是效果沒想像的好,尤其是在Mobile Browsers上。
不過這也是WebAssembly打算改善的問題,目前只有Edge跟Firefox支援Asm.js程度比較高。
在FFmpeg這項目吃盡苦頭,寫個筆記紀錄怎麼認真玩Emscripten。
我是參考audioconverter.js不過用他的Script無法使用。只好自行摸索出適合的方式。

我的目標市 FFmpeg + fdk_aac ,接下來的教學就是如何做出一個包涵這兩樣的 Javascript

Build FDK AAC

這個跟一般的玩Emscripten玩法沒差太多

1
2
3
4
5
6
7
8
9
10
11
$ git clone https://github.com/mstorsjo/fdk-aacsed -i 's/gcc/emcc/g' config.mak
$ cd fdk-aac
$ ./autogen.sh
$ emconfigure ./configure --prefix=/home/hm/local
$ emmake make
$ make install
```sed -i 's/gcc/emcc/g' config.makdd

### Build FFMpeg
這才是花了很多時間在Try and Error上,照AudioConvert.JS那樣寫對我來說就是沒用
因為原先emconfigure的方式無法抓到 libfdk_aac,只好手動用原先的方式來作

$ cd ffmpeg
$ PKG_CONFIG_PATH=/home/hm/local/lib/pkgconfig/ ./configure –disable-asm –disable-outdevs –disable-indevs –disable-filters –disable-bsfs –disable-decoders –enable-decoder=mp3,h264 –disable-demuxers –enable-demuxer=mpegts –disable-muxers –enable-muxer=mpegts –disable-protocols –enable-protocol=file –enable-libfdk-aac –disable-encoders –enable-encoder=libfdk_aac –enable-filter=aresample –disable-parsers –disable-doc –disable-stripping –disable-protocol=rtp,tcp,udp,http –disable-pthreads –disable-debug –disable-network –enable-parser=h264 –disable-filter=crop –extra-cflags=-I/home/hm/local/include

1
產生完config.mak之後在手動改掉

$ sed -i ‘s/gcc/emcc/g’ config.mak
$ sed -i ‘s/g++/emcc/g’ config.mak
$ sed -i ‘s/VALGRIND_H 1/VALGRIND_H 0/g’ config.h
$ make

1
如果沒意外的話彙編出**不能動**的ffmpeg,不過在意料之中,編譯過程中也會告訴你沒有找到`fdk-aac`,這都無所謂,畢竟這只是中間產物,要進行最後的動作才行。

$ mv ffmpeg ffmpeg.bc
$ emcc -O2 ffmpeg.bc /home/hm/local/lib/libfdk-aac.a -o ffmpeg.js

1
接著我們用nodejs試著執行看看

$ node ffmpeg.js
ffmpeg version 3.1.1 Copyright (c) 2000-2016 the FFmpeg developers

1
2
3
4
成功了,不過還是不能在網頁上用
### Runs inside browsers
參考AudioConvert.js的方式,將`ffmpeg-pre.js`和`ffmpeg-post.js`複製出來
進行編譯

$ emcc -g4 -Os –memory-init-file 0 ffmpeg.bc /home/hm/local/lib/libfdk-aac.a -o ffmpeg.js –pre-js ffmpeg_pre.js –post-js ffmpeg_post.js

```
然後將ffmpeg.js複製到audioconvert.js中的測試網頁中,就能看到他能夠動作了

Conclusion

emcc的表現真的有夠怪異,如果在網頁版的編譯加上-g3以上等級的debuger info,編出來的東西跟本部能用。
編譯的過程更是痛苦連連,效果也不如想像中的好
希望WebAssembly可以彌補這一塊

根據這篇這篇,C++17的最終定案即將出爐。之前喊得狒狒洋洋的moduleconceptcoroutine沒有一個列為標準配備。相對之前喊得狒狒洋洋的大變動。還真是雷聲大雨點小。
不過還是有些實用的技術可以馬上用到,學習曲線沒那麼高..
不過這年頭每個程式語言都在新增新特性,像C語言這種實在難能可貴。不過C太低階了,開發大程式實在很麻煩。真是兩難

Structured bindings

之前說過,C++沒有return multiple value的機制,要做出類似的小果只能這麼做。

1
2
3
4
std::tuple<bool, int> getValue();
bool retB;
int retInt;
std::tie(retB, retInt) = getValue();

可以用,不過不太美觀。到了C++17有了更直觀的方法

1
auto [retB, retInt] = getValue();

這樣就很像go的語法了。更多的討論可以看Returning multiple values from functions in C++

If statement with initializer

這也是另一個我覺得很棒的點
直接看範例,為進化前

1
2
3
4
5
6
7
8
9
status_code foo() { 
{
status_code c = bar();
if (c != SUCCESS) {
return c;
}
}
// ...
}

進化後,可能的情況

1
2
3
4
5
6
status_code foo() {
if (status_code c = bar(); c != SUCCESS) {
return c;
}
// ...
}

希望這兩點未來C語言也會加回去啊

C/C++寫久了,為了轉換心情,開發了一個玩具Website Parser。把太過複雜的網頁元素清掉,只留下Title跟必要的資訊。
採用的是Python3跟BeautifulSoup4,雖然Python的文章看了不少。不過這倒是第一次認真寫點東西(雖然也只是個玩具)

獲取網頁資訊

用最簡單的方式來獲取網頁,方法不是最好,但是可以用。

1
2
3
4
def getHtml(url):
htmlDoc = request.urlopen(url).read()
htmlDoc = htmlDoc.decode('UTF-8')
return htmlDoc

將html轉成 Beautiful Soup Object

1
soup = BeautifulSoup(htmlDoc, "lxml")

砍掉無謂的網頁元件

砍掉所有符合條件的 Tag

1
2
for script in soup.find_all('script'):
script.decompose()

砍掉特定的 Tag

1
2
3
div = soup.find("div", {"id": "full-btm"})
if div is not None:
div.decompose()

砍掉 Tag中的某個屬性

1
2
3
div = soup.find("div", {"id": "full-btm"})
if div is not None:
del div["attribute"]

把清除過的 Soup 存回 HTML

1
2
3
4
html = soup.prettify("utf-8")

with open("output.html", "wb") as file:
file.write(html)

雖然只是個玩具,不過至少對Python有多一點感覺了,寫完之後才發現Sanitize HTML with Beautiful Soup這篇早就有了,真是後知後覺好幾年。