有没有办法以通配符的方式用模板类声明 friend ?
例子
我总是这样声明 friend :-
//B.h
template<class T1,class T2>class B{};
//C.h
class C{
template<class,class> friend class B;
};
但是,如果 B
模板参数发生变化,我将不得不更新 C
,它通常是一个相距很远的 header 。
//B.h
template<int T3,class T1,class T2>class B{};
//C.h
class C{
template<int,class,class> friend class B; //<-- manually update here too
};
它会导致轻微的可维护性问题。 (对我来说,每周一次。)
问题
我可以做这样的事情吗?
class C{
template<ANY...> friend class B;
};
这是不可能的吗?
我隐约觉得这个问题可能重复了,因为这可能是一个普遍的问题。
但是,我找不到。
最佳答案
这是一种方法:
// declare the concept of a variadic B
template<class...Ts> struct B;
struct C
{
private:
// any B with any number of Types is a friend
template<class...Ts> friend struct B;
void privateThing() {};
};
// now specialise B <T1, T2>
template<class T1, class T2> struct B<T1, T2> {
void foo(C& c) {
c.privateThing();
}
};
int main()
{
C c;
B<int, double> b;
b.foo(c);
}
关于c++ - 具有特定模板类 : "template<ANY...> friend class A;" 的 friend ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44093033/