std::ios_base::register_callback
void register_callback( event_callback function, int index ); | | |
---|
注册用户定义的函数,该函数将由imbue()
,,,std::basic_ios::copyfmt()
和~ios_base()
.每次调用每个已注册回调:事件类型%28a值的类型event
%29作为其第一个参数传递,可用于区分调用方。
回调按注册%28的相反顺序调用,换句话说,register_callback()
在回调堆栈%29上推送回调对。如果register_callback()
从回调函数中调用以添加新回调,则只在下一个事件中调用新回调。
用户定义的回调函数不允许抛出异常。
参数
function | - | the function which will be called on event, supplied as a function pointer of type event_callback |
---|---|---|
index | - | custom parameter which will be passed to the function |
返回值
%280%29
注记
一旦注册,回调就不能取消注册:它在其剩余的生命周期中始终是流对象的一部分。如果回调的行为需要更改,则可以通过iword()
或pword()
...
如果同一个函数多次注册,则称为多次。
与回调一起存储的整数值通常是从xalloc()
...
例
演示寄存器的使用。[医]回调以更新自定义输出运算符使用的依赖于区域设置的缓存值。
二次
#include <iostream>
#include <locale>
#include <functional>
// cached locale-specific message and its hash
typedef std::pair<std::string, std::size_t> cache_t;
// populate the cached message and its hash from the locale
void update_cache(cache_t& cache, std::locale loc)
{
auto& fct = std::use_facet< std::messages<char> >(loc);
std::messages_base::catalog cat = fct.open("sed", loc);
cache.first = cat < 0 ? "" : fct.get(cat, 0, 0, "Memory exhausted");
cache.second = std::hash<std::string>()(cache.first);
}
// update the cache if the locale changed
void true_callback(std::ios_base::event evt, std::ios_base& str, int idx)
{
if (evt == std::ios_base::imbue_event)
{
cache_t* ptr = static_cast<cache_t*>(str.pword(idx));
update_cache(*ptr, str.getloc());
}
}
// registers the cache in pword() and sets up the callback
struct CacheSetup
{
CacheSetup(std::ostream& os, std::ios_base::event_callback f, cache_t* cache)
{
int index = std::ostream::xalloc();
os.pword(index) = cache; // store pointer to cache in the stream
os.register_callback(f, index); // store callback and the index to the pointer
update_cache(*cache, os.getloc()); // initialize cache
};
};
// some custom class
struct S { };
// some custom class's operator<< that needs fast access to hashed message
std::ostream& operator<<(std::ostream& os, const S&)
{
static cache_t cache;
static CacheSetup setup(os, true_callback, &cache);
return os << cache.first << " : " << cache.second;
}
int main()
{
std::locale loc("en_US.utf8");
S s;
std::cout.imbue(loc);
std::cout << s << '\n';
std::cout.imbue(std::locale(loc, new std::messages_byname<char>("de_DE.utf8")));
std::cout << s << '\n';
std::cout.imbue(std::locale(loc, new std::messages_byname<char>("ja_JP.utf8")));
std::cout << s << '\n';
std::cout.imbue(std::locale(loc, new std::messages_byname<char>("ru_RU.utf8")));
std::cout << s << '\n';
}
二次
产出:
二次
Memory exhausted : 2,295,079,096
Speicher erschöpft : 3,139,423,551
メモリーが足りません : 3,837,351,114
Память исчерпана : 3,742,732,851
二次
© cppreference.com
在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。
本文档系腾讯云开发者社区成员共同维护,如有问题请联系 cloudcommunity@tencent.com