ディートマーが言ったように、パラメーターを iword() にプッシュすることができますが、この種の解決策は面倒で面倒です..
私は単にラムダ関数を iomanips としてインストールし、それらを使用してさまざまなクラス メソッドを直接呼び出すか、カスタム プリントをその場で構築することを好みます。その目的のために、任意のクラスのマニピュレーターとしてラムダ関数を追加できるメインピュレーター用の単純な 100 行のテンプレート インストーラー/ヘルパー クラスを作成しました。
したがって、CDateの場合、manipを次のように定義できます
std::ostream& dummy_date_format_manipulator (std::ostream& os)
{
CustomManip<CDate>::install(os,
[](std::ostream& oos, const CDate& a)
{
os << a.year()
<< "-hello-"
<< a.day()
<< "-world-"
<< a.month()
<< "-something-"
<< a.day() << a.day();
});
return os;
}
次に、 << op に manip インストーラーの印刷ヘルパーを使用するように指示します。
std::ostream& operator<<(std::ostream& os, const CDate& a)
{
CustomManip<CDate>::print(os, a);
return os;
}
そして、あなたの基本的に完了..
mainpインストーラー コードと完全に機能する例は、次のブログ投稿にあり
ます。
しかし、いいことに..これが.hに入れたい重要な部分であり、それがどのように機能するかを示すためにすべてのプリントアウトを減らします:
//g++ -g --std=c++11 custom_class_manip.cpp
#include <iostream>
#include <ios>
#include <sstream>
#include <functional>
template <typename TYPE>
class CustomManip
{
private:
typedef std::function<void(std::ostream&, const TYPE&)> ManipFunc;
struct CustomManipHandle
{
ManipFunc func_;
};
static int handleIndex()
{
// the id for this Custommaniputors params
// in the os_base parameter maps
static int index = std::ios_base::xalloc();
return index;
}
public:
static void install(std::ostream& os, ManipFunc func)
{
CustomManipHandle* handle =
static_cast<CustomManipHandle*>(os.pword(handleIndex()));
// check if its installed on this ostream
if (handle == NULL)
{
// install it
handle = new CustomManipHandle();
os.pword(handleIndex()) = handle;
// install the callback so we can destroy it
os.register_callback (CustomManip<TYPE>::streamEvent,0);
}
handle->func_ = func;
}
static void uninstall(std::ios_base& os)
{
CustomManipHandle* handle =
static_cast<CustomManipHandle*>(os.pword(handleIndex()));
//delete the installed Custommanipulator handle
if (handle != NULL)
{
os.pword(handleIndex()) = NULL;
delete handle;
}
}
static void streamEvent (std::ios::event ev,
std::ios_base& os,
int id)
{
switch (ev)
{
case os.erase_event:
uninstall(os);
break;
case os.copyfmt_event:
case os.imbue_event:
break;
}
}
static void print(std::ostream& os, const TYPE& data)
{
CustomManipHandle* handle
= static_cast<CustomManipHandle*>(os.pword(handleIndex()));
if (handle != NULL)
{
handle->func_(os, data);
return;
}
data.printDefault(os);
}
};
もちろん、本当にパラメーターが必要な場合は、CustomManip::make_installer(...) 関数を使用してそれを実行しますが、そのためにはブログにアクセスする必要があります..