我看到了一个CRTP溶液,它将接口提取到基类中,并且只为每个基类提供了一个pack参数。然后,大多数派生类继承了所有的好友基类,并实现了接口。
我不能使用这种方法,因为我需要保护赋值操作符,它不是继承的。
另外,由于赋值运算符有一个定义的签名,并且只有一个参数,所以我不能使用键模式。
这就是我想要的:
template <typename... F>
struct A {
protected:
A& operator=(const SomeClass &other) {
//...
}
private:
//I would like to do the following, but it does not work
friend F...;
}
有办法满足我的需要吗?
发布于 2015-07-20 02:30:44
好吧,你总是可以玩脏的。首先,定义一个重复宏:
#define REPEAT_2(M, N) M(N) M(N+1)
#define REPEAT_4(M, N) REPEAT_2 (M, N) REPEAT_2(M, N+2)
#define REPEAT_8(M, N) REPEAT_4 (M, N) REPEAT_4(M, N+4)
#define REPEAT_16(M, N) REPEAT_8 (M, N) REPEAT_8(M, N+8)
#define REPEAT_32(M, N) REPEAT_16 (M, N) REPEAT_16(M, N+16)
#define REPEAT_64(M, N) REPEAT_32 (M, N) REPEAT_32(M, N+32)
#define REPEAT_128(M, N) REPEAT_64 (M, N) REPEAT_64(M, N+64)
然后将128个朋友声明放入您选择的各种类模板中:
template <typename... T>
class A
{
#define FRIEND(N) friend std::tuple_element_t<
std::min((std::size_t)N+1, sizeof...(T)), std::tuple<void, T...>>;
REPEAT_128(FRIEND, 0)
static constexpr int i = 3;
};
struct X; struct Y; struct Z;
using ASpec = A<X, Y, Z>;
struct X {int i = ASpec::i;};
struct Y {int i = ASpec::i;};
struct Z {int i = ASpec::i;};
template class A<>; // Small test for empty pack
演示。归功于@dyp。
如果您能够访问Boost.Preprocessor,则可以使用BOOST_PP_REPEAT
编写更简洁的整个程序。
https://stackoverflow.com/questions/31510844
复制