我一直在研究为我的C++项目编写一个static_if,然后我偶然发现了下面这段代码:
#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
中重载的运算符()。它接受类型为T的rhs(右值)作为参数x,很酷。但是当调用identity
时,实际上没有传入任何参数。
template<typename F>
void then(const F& f){
f(identity());
}
上面的代码中,f 调用了 identity 函数,但是没有向其传递任何参数。然而,identity 函数返回被转发的参数(在我的例子中是 std::string),并弹出字符串的最后一个字符。 当 identity 函数本身没有传入任何要转发的参数时,它如何返回被转发的参数呢?
f
看起来是一个函数,并且它被调用时带有一个类型为identity
的单个参数。换句话说,identity()
构造了一个identity
类型的实例,该实例被传递给f
函数。 - James Adkison