我一直在尋找到寫static_if我的C++的項目,我偶然發現了下面的一段代碼:的std ::向前和運營商()
#include <iostream>
using namespace std;
namespace static_if_detail {
struct identity {
template<typename T>
T operator()(T&& x) const {
return std::forward<T>(x);
}
};
template<bool Cond>
struct statement {
template<typename F>
void then(const F& f){
f(identity());
}
template<typename F>
void else_(const F&){}
};
template<>
struct statement<false> {
template<typename F>
void then(const F&){}
template<typename F>
void else_(const F& f){
f(identity());
}
};
} //end of namespace static_if_detail
template<bool Cond, typename F>
static_if_detail::statement<Cond> static_if(F const& f){
static_if_detail::statement<Cond> if_;
if_.then(f);
return if_;
}
template<typename T>
void decrement_kindof(T& value){
static_if<std::is_same<std::string, T>::value>([&](auto f){
f(value).pop_back();
}).else_([&](auto f){
--f(value);
});
}
int main() {
// your code goes here
std::string myString{"Hello world"};
decrement_kindof(myString);
std::cout << myString << std::endl;
return 0;
}
這一切對我來說很有意義,除了有一件事:重載運算符()在struct identity
。它採用稱爲x的T型rhs,很酷,全部。但是當調用identity
時,實際上沒有任何東西傳入身份。
template<typename F>
void then(const F& f){
f(identity());
}
上面,f調用標識,但沒有傳遞任何標識。然而,身份返回轉發的參數(在我的情況下,一個std ::字符串),並彈出字符串的最後面的字符。 身份如何返回一個轉發的參數,當它本身沒有參數傳遞給它轉發?
對我來說,它看起來像'f'是一個函數,它是用'identity'類型的單個參數調用的。換句話說,'identity()'構造了傳遞給'f'函數的'identity'類型的一個實例。 –
[This](http://ideone.com/p8SlI9)是它看起來像構建和調用一個類似的對象。 –