C++ boost::variant as friend类

C++ boost::variant as friend类,c++,boost,c++98,boost-variant,C++,Boost,C++98,Boost Variant,对于我想在boost::variant中使用的类型Foo,我想将默认构造函数设置为private,因为它只允许由boost::variant调用 遗憾的是,我还不能理解boost::variant的声明魔法,而仅仅是声明 struct Foo { private: Foo(); template <class T1, class T2> friend class boost::variant<T1, T2>; }; structfoo{ 私人: Foo();

对于我想在
boost::variant
中使用的类型
Foo
,我想将默认构造函数设置为
private
,因为它只允许由
boost::variant
调用

遗憾的是,我还不能理解
boost::variant
的声明魔法,而仅仅是声明

struct Foo {
private:
  Foo();
  template <class T1, class T2>
  friend class boost::variant<T1, T2>;
};
structfoo{
私人:
Foo();
模板
好友类boost::variant;
};

也没有编译。有没有办法做到这一点,或者我是否需要保持
Foo()
公共

[此答案仅针对C++98/03;有关现代代码,请参见下文]

boost::variant
的模板参数数量由下式给出。您可以通过以下方式使用它:

将扩展到:

class T0, class T1, class T2, class T3, class T4


请注意,上述内容适用于问题的范围,即仅限于C++98/03。由于C++11存在可变模板,当这些模板可用于Boost时,
Boost\u VARIANT\u LIMIT\u type
未定义,且上述代码不起作用。Boost提供了一种既可以使用变量也可以不使用变量的替代方案;有关详细信息,请参阅。

当可变模板可用时,您必须使用
模板友元类boost::variant否则会出现错误:“BOOST\u PP\u REPEAT\u 1\u BOOST\u VARIANT\u LIMIT\u TYPES”尚未声明

这里有一个最低要求:

#包括
#包括
结构Foo{
公众:
Foo(int){};
私人:
Foo();
模板好友类boost::variant;
int i;
};
int main()
{
富富(10),;
boost::variant test=foo;
}

我认为这不能保证实例化代码是
boost::variant
本身,而不是它的一个助手类。但我还没有研究实现。也许这是文档化界面的一部分。@Cheersandhth.-Alf说得好。我回答了“如何与
boost::variant
交朋友”的问题,而不是更广泛的问题“如何与
boost::variant
一起使用私人ctor”。我将把它留给OP来决定它是否对他们有效;我愿意被一个更好的答案击败,并且/或者在发现不足的情况下撤回我的答案。我检查了
boost::variant
是否进行了实例化,然后:)。这就是说,该提案至少在VS2010的identifier
BOOST\u PP\u REPEAT\u 1\u class
@abergmeier哇,我不小心换了参数顺序。更正。我必须使用
模板friend class boost::variant取而代之。否则,我有一个关于“BOOST\u PP\u REPEAT\u 1\u BOOST\u VARIANT\u LIMIT\u TYPES”未声明的错误
BOOST_PP_ENUM_PARAMS(5, class T)
class T0, class T1, class T2, class T3, class T4
#include <boost/variant.hpp>
#include <boost/preprocessor/repetition/enum_params.hpp>

struct Foo {
public:
    Foo(int){};
private:
    Foo();
    template <BOOST_VARIANT_ENUM_PARAMS(class T)> friend class boost::variant;
    int i;
};

int main()
{
    Foo foo(10);
    boost::variant<Foo> test=foo;
}