我正在存储需要对对象进行操作的操作,但我不想使用继承.所以我使用的技术是拥有一个非成员函数,它接受一个指向对象的指针,然后将它存储在对象中,如下所示:
struct command
{
command()
{
}
command(const std::function<void()>& action)
: action(action)
{
}
int n;
std::function<void()> action;
};
void test_action(command* this_ptr)
{
this_ptr->n = 5;
}
int main()
{
command com(std::bind(test_action, &com));
com.action();
std::cout << com.n;
}
Run Code Online (Sandbox Code Playgroud)
我的问题是安全command com(std::bind(test_action, &com));吗?还是未定义的行为?
处理const向量时,以下方法不起作用:
const std::vector<std::string> v;
v.push_back("test"); // error: v cannot be modified
Run Code Online (Sandbox Code Playgroud)
相反,您必须在构造它的同一行初始化向量.但是,即使有这个限制,boost::make_transform_iterator也可以在将它们推入v之前轻松地使用另一个vector的元素.在这个例子中,convert是一个返回输入元素的转换版本的一元函数:
auto beg = boost::make_transform_iterator(args.begin(), convert);
auto end = boost::make_transform_iterator(args.end(), convert);
const std::vector<const char*> vc { beg, end };
Run Code Online (Sandbox Code Playgroud)
我已经看了可用的功能<iterator>,但没有看到等效功能.它只是缺失或标准库没有它的原因吗?
我收到编译错误,发现有趣的东西.由于某种原因unique_ptr有一个超载auto_ptr,但我认为auto_ptr已被弃用:
/usr/local/include/c++/4.9.0/bits/unique_ptr.h:228:2:
note:template<class _Up, class>
std::unique_ptr<_Tp, _Dp>::unique_ptr(std::auto_ptr<_Up>&&)
unique_ptr(auto_ptr<_Up>&& __u) noexcept;
/usr/local/include/c++/4.9.0/bits/unique_ptr.h:228:2:
note: template argument deduction/substitution failed:
main.cpp:41:67: note: mismatched types 'std::auto_ptr<T>' and 'char*'
Run Code Online (Sandbox Code Playgroud)
这是因为与使用的代码向后兼容auto_ptr吗?