kyk*_*yku 9 c++ templates boost friend make-shared
我编写了一个带有受保护构造函数的类,因此只能使用静态create()函数生成新实例,该函数将shared_ptr返回给我的类.为了提供有效的分配,我想在create函数中使用boost :: make_shared,但是编译器抱怨我的类构造函数在boost :: make_shared中受到保护.我决定将我的boost :: make_shared作为我班上的朋友,但我对语法感到困惑.我试过了
template< class T, class A1, class A2 >
friend boost::shared_ptr<Connection> boost::make_shared(const ConnectionManagerPtr&, const std::string&);
Run Code Online (Sandbox Code Playgroud)
但是编译器给了我语法错误.请帮忙.
Geo*_*che 10
您不需要模板化friend
部件,但需要表明该friend
功能是模板:
friend boost::shared_ptr<Connection> boost::make_shared<>(/* ... */);
// ^^
Run Code Online (Sandbox Code Playgroud)
这适用于Comeau和当前的GCC版本,但与VC失败.更好的是以下形式:
friend boost::shared_ptr<Connection> boost::make_shared<Connection>(/* ... */);
Run Code Online (Sandbox Code Playgroud)
这适用于多个编译器 - 我在VC8,VC10,GCC 4.2,GCC 4.5和Comeau 4.3上进行了测试.
或者使用一个合格的名称来指代功能模板马丁没有的特定实例应该工作,并与科莫的做法,但GCC扼流圈就可以了.
一个不依赖于实现细节的有用替代方案make_shared()
(因此也适用于VC10s TR1实现)是使用pass-key-idiom对构造create()
函数进行访问保护并改为与函数成为联系,例如:
class Connection {
// ...
public:
class Key {
friend boost::shared_ptr<Connection> create(const ConnectionManagerPtr&,
const std::string&);
Key() {}
};
Connection(const ConnectionManagerPtr&, const std::string&, const Key&);
};
boost::shared_ptr<Connection> create(const ConnectionManagerPtr& p,
const std::string& s)
{
return boost::make_shared<Connection>(p, s, Connection::Key());
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7549 次 |
最近记录: |