我一直在寻找到写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)是它看起来像构建和调用一个类似的对象。 –