티스토리 뷰
ostream 에 1이 출력되는 이유는, pointer가 bool 로 바껴서 그렇다
bool check 로 생각하면됨
전역 lambda capture로 1로 변환됨;
https://lunapiece.net/Article/14007902
https://stackoverflow.com/questions/21958261/outputstream-prints-1-for-some-reason
https://stackoverflow.com/questions/2064692/how-to-print-function-pointers-with-cout
// 27.7.2.6 Formatted output:
inline _LIBCPP_HIDE_FROM_ABI_AFTER_V1
basic_ostream& operator<<(basic_ostream& (*__pf)(basic_ostream&))
{ return __pf(*this); }
Why C++ Member Function Pointers Are 16 Bytes Wide
http://lazarenko.me/wide-pointers/
void call_by_ptr(const C &obj, void (C::*mem_func)() const)
{
void *data[2];
std::memcpy(data, &mem_func, sizeof(mem_func));
std::cout << "------------------------------\n"
"Object ptr:\t" << &obj <<
"\nFunction ptr:\t" << data[0] <<
"\nPointer adj:\t" << data[1] << std::endl;
(obj.*mem_func)();
}
#include <iostream>
#include <cstdint>
#include <vector>
#include <array>
#include <sstream>
#include <string>
#include <iostream>
namespace function_display
{
template<class Ret, class... Args>
std::ostream& operator <<(std::ostream& os, Ret(*p)(Args...))
{
return os << "funptr " << (void*)p;
}
}
// example code:
void fun_void_void() {};
void fun_void_double(double d) {};
double fun_double_double(double d) { return d; }
using Callback = void(*)(void* buffer, size_t size, void* user);
static const auto FREE_CALLBACK = [](void* mem, size_t size, void* user) { free(mem); };
struct stream
{
stream& operator<<(stream& (* f)(stream&)) noexcept {
return f(*this);
}
stream& operator<<(const void* value) noexcept {
return *this;
}
stream& operator<<(bool value) noexcept {
return *this;
}
template<class Ret, class... Args>
stream& operator<<(Ret(*p)(Args...))
{
*this << "funptr " << (void*)p;
return *this;
}
};
int main()
{
using namespace function_display;
// ampersands & are optional
std::cout << "1. " << &fun_void_void << std::endl; // prints "1. funptr 0x40cb58"
std::cout << "2. " << &fun_void_double << std::endl; // prints "2. funptr 0x40cb5e"
std::cout << "3. " << &fun_double_double << std::endl; // prints "3. funptr 0x40cb69"
std::cout << "4. " << FREE_CALLBACK << std::endl; // prints "4. 1"
std::cout << "5. " << &FREE_CALLBACK << std::endl; // prints "5. 0x100001f57"
Callback callback = FREE_CALLBACK;
std::cout << "6. " << callback << std::endl; // prints "6. funptr 0x1000001240"
stream out;
out << FREE_CALLBACK; // bool value
out << &FREE_CALLBACK; // const void*
out << callback; // funptr
out << &callback; // const void*
return 0;
}
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크