jos*_*shu 6 c++ gcc boost c++11 raspberry-pi
您好我有以下代码:
bool PinManager::insertPin(const std::string& p_pinNumber, const std::string& p_mode)
{
boost::shared_ptr<GPIOPin> pin(new GPIOPin(p_pinNumber, p_mode));
if (pin)
{
m_pinsInUse.insert(std::make_pair<std::string, boost::shared_ptr<GPIOPin> >(p_pinNumber, pin));
return true;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
这段代码总是被编译,但是当我添加-std=c++0x标志时,这段代码无法使用以下消息进行编译:
[ 42%] Building CXX object gpioaccess/CMakeFiles/gpioaccess.dir/pinmanager/pinmanager.cpp.o
/home/pi/robot_2.0/trunk/gpioaccess/pinmanager/pinmanager.cpp: In member function 'bool gpioaccess::PinManager::insertPin(const string&, const string&)':
/home/pi/robot_2.0/trunk/gpioaccess/pinmanager/pinmanager.cpp:39:101: error: no matching function for call to 'make_pair(const string&, boost::shared_ptr<gpioaccess::GPIOPin>&)'
/home/pi/robot_2.0/trunk/gpioaccess/pinmanager/pinmanager.cpp:39:101: note: candidate is:
/usr/include/c++/4.6/bits/stl_pair.h:262:5: note: template<class _T1, class _T2> std::pair<typename std::__decay_and_strip<_T1>::__type, typename std::__decay_and_strip<_T2>::__type> std::make_pair(_T1&&, _T2&&)
gpioaccess/CMakeFiles/gpioaccess.dir/build.make:77: recipe for target 'gpioaccess/CMakeFiles/gpioaccess.dir/pinmanager/pinmanager.cpp.o' failed
make[2]: *** [gpioaccess/CMakeFiles/gpioaccess.dir/pinmanager/pinmanager.cpp.o] Error 1
CMakeFiles/Makefile2:75: recipe for target 'gpioaccess/CMakeFiles/gpioaccess.dir/all' failed
make[1]: *** [gpioaccess/CMakeFiles/gpioaccess.dir/all] Error 2
Makefile:75: recipe for target 'all' failed
make: *** [all] Error 2
Run Code Online (Sandbox Code Playgroud)
在做了一点挖掘之后,我发现之前编译的事实可能是一个bug; 但是,我仍然不确定如何解决这个问题.有没有人有正确的方向?
gcc --version 是 gcc (Debian 4.6.3-14+rpi1) 4.6.3
Pio*_*cki 24
std::make_pair在c ++ 03和c ++ 11之间发生了变化.
在c ++ 11中,它通过转发引用而不是值接受参数.这意味着通过明确指定其类型模板参数,您最终会得到以下实例化:
std::make_pair<std::string , boost::shared_ptr<GPIOPin> >
(std::string&&, boost::shared_ptr<GPIOPin>&&);
Run Code Online (Sandbox Code Playgroud)
期望rvalue引用,它不能绑定到左值.
您不应该明确指定类型模板参数std::make_pair.相反,你应该让编译器自己推导出它们:
std::make_pair(p_pinNumber, pin)
Run Code Online (Sandbox Code Playgroud)
另外,从c ++ 11开始,在使用时std::map,您可以就地构建对:
m_pinsInUse.emplace(p_pinNumber, pin);
Run Code Online (Sandbox Code Playgroud)
在c ++ 17中,您可以利用类模板参数推导,并在std::pair不指定类模板参数的情况下构造:
std::pair(p_pinNumber, pin)
Run Code Online (Sandbox Code Playgroud)
重点std::make_pair是简化创建,std::pair因此您不需要指定模板参数,让编译器推导出它们.
如果你std::make_pair<T, U>(t, u)使用显式模板参数进行调用,那么你正在击败函数的整个目的,因为你正在阻止演绎,而你正在浪费时间输入额外的字符并可能创建不必要的对象副本,而你可以这样做std::pair<T, U>(t, u)(保存自己)从键入五个额外的,无用的字符).
如果您使用std::make_pair它的预期方式,那么您甚至不会注意到它在C++ 11中发生了变化.如果你通过毫无意义地提供模板参数来滥用它,那么它可能在C++ 11中不起作用,所以不要这样做.
我在http://advogato.org/person/redi/diary/239.html上写了一个更完整的解释
请注意,在c ++ 11中,通常可以删除std :: make_pair以支持初始化构造函数
m_pinsInUse.insert({p_pinNumber, pin});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6067 次 |
| 最近记录: |