2014-04-25 4 views

답변

12

Functionoperator()에 ref 한정자가있는 경우 차이가 있습니다. std::forward을 사용하면 인수의 값 범주가 전파되고 값 범주는 손실되며 함수는 항상 l 값으로 호출됩니다. Live Example.

#include <iostream> 

struct Fun { 
    void operator()() & { 
     std::cout << "L-Value\n"; 
    } 
    void operator()() && { 
     std::cout << "R-Value\n"; 
    } 
}; 

template <class Function> 
void apply(Function&& function) { 
    function(); 
} 

template <class Function> 
void apply_forward(Function&& function) { 
    std::forward<Function>(function)(); 
} 

int main() { 
    apply(Fun{});   // Prints "L-Value\n" 
    apply_forward(Fun{}); // Prints "R-Value\n" 
} 
+0

언제부터 멤버 한정자 선언에 ref 한정자를 적용 할 수 있습니까? – Deduplicator

+2

@Deduplicator : 2011 년부터 –

+0

@ 중복 제거기 :'C++ 11' 이후. 이 기능은 [n2439] (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2439.htm)에 설명되어 있습니다. [here] (http://en.cppreference.com/w/cpp/language/member_functions) 및 [here] (http://stackoverflow.com/q/8610571/485561)를 참조하십시오. – Mankarse