2017-07-28 121 views
3

所以說,我想做一些constexpr函數,我雖然可以使用bind做到這一點。有什麼我失蹤? bind爲什麼不能返回constexpr爲什麼我無法獲得綁定?

考慮:

struct foo { 
    int b() const { return _b; } 
    int a() const { return _a; } 
    int r() const { return _r; } 
    const int _b; 
    const int _a; 
    const int _r; 
}; 

我想:

constexpr auto sumB = bind(plus<int>(), placeholders::_1, bind(&foo::b, placeholders::_2)); 
constexpr auto sumA = bind(plus<int>(), placeholders::_1, bind(&foo::a, placeholders::_2)); 
constexpr auto sumR = bind(plus<int>(), placeholders::_1, bind(&foo::r, placeholders::_2)); 

有什麼我可以做,以使這項工作?

+2

的問題可能是現在「爲什麼不能」,而是「爲什麼沒有按「T」。它可能會,但事實並非如此。 –

+0

@NathanOliver我認爲這將是一個很好的答案。你介意張貼嗎? –

回答

5

不存在技術障礙,使bind constexpr;例如,Sprout C++ Librariesconstexpr-enabled bind

但是,implementations are not permitted to add constexpr to function signatures where it is not specified in the Standard,並且還沒有任何提議將constexpr添加到我知道的bindWhich parts of the C++14 Standard Library could be and which parts will be made constexpr?)。這是相當不可能的,一個是即將到來的,因爲bindmostly superseded通過lambda表達式,其形式爲C++ 17自動constexpr:

constexpr auto sumB = [](int x, foo const& y) { return x + y.b(); }; 
+0

這太好了,因爲它回答了我爲什麼當它們無法像lambda表達式捕獲時那樣'bind' results'constexpr'的深層問題,因此在編譯時應該是完全可定義的。 –

3

那麼,我們不知道什麼std::bind返回。它可能會工作,但沒有任何要求使其工作(沒有任何東西在std::bind的規範中定義爲constexpr)。

在你可以做的事情上,如果你有權訪問C++ 17,那就是使用lambda。在C++ 17的拉姆達的operator()將被標記爲默認constexpr允許你這樣做

constexpr auto sumB = [](auto val, auto obj) { return val + obj.b(); }; 
constexpr auto sumA = [](auto val, auto obj) { return val + obj.a(); }; 
constexpr auto sumR = [](auto val, auto obj) { return val + obj.r(); }; 

Live Example

+0

'std :: bind'無法返回'std :: function'。 – Yakk

+0

@Yakk好吧,TIL。感謝您的信息。答案已被編輯。 – NathanOliver

+0

如果你想知道爲什麼,'std :: bind'的返回值必須有一個模板化的'operator()',*和*它傳遞給另一個綁定表達式時必須有某些屬性; 'std :: function'沒有這些屬性。 – Yakk

相關問題