mat*_*ati 5 c++ templates friend variadic-templates c++11
我正在尝试使用可变参数模板来指定朋友类。我尝试使用以下语法,但是不起作用。
template <class... Args>
struct A {
friend Args...;
};
Run Code Online (Sandbox Code Playgroud)
我尝试编写一些变通办法,但是由于友谊不是可传递的和继承的,因此似乎并不是那么简单。因此,问题是是否存在正确的语法或任何变通方法,以使Args中的每个单独的类成为A的朋友?
也许以下 CRTP 变体足以满足您的使用:
template<typename Arg> class Abase
{
friend Arg;
virtual int foo(int) = 0; // this is the private interface you want to access
public:
virtual ~Abase() {}
};
template<typename... Args> class A:
public Abase<Args> ...
{
virtual int foo(int arg) { return frobnicate(arg); }
// ...
}
Run Code Online (Sandbox Code Playgroud)
然后你传入Args的每个类都可以通过相应的Abase基类访问该私有接口,例如
class X
{
public:
// assumes X is in the Args
template<typename Args ...> int foo(A<Args...>* p)
{
Abase<X>* pX = p; // will fail if X is not in Args
return pX->foo(3); // works because X is friend of Abase<X>
}
};
Run Code Online (Sandbox Code Playgroud)