#include <cstdio>
class builtin_pack
{
long v[4];
public:
builtin_pack ( long v1, long v2, long v3, long v4 ) : v{v1, v2, v3, v4} {}
void builtin_op()
{
printf ( "%lx,%lx,%lx,%lx\n", v[0], v[1], v[2], v[3] );
};
template<typename Func, typename... Targs>
void builtin_apply ( Func f, Targs ... t )
{
for ( int i = 0; i < 4; i++ )
{
v[i] = f ( t.v[i]... );
}
}
};
class pack : builtin_pack
{
public:
pack ( long v1, long v2, long v3, long v4 ) : builtin_pack ( v1, v2, v3, v4 ) {}
template<typename Func, typename... Targs>
pack& apply ( Func f, Targs ... t )
{
this->builtin_apply ( f, t... );
return *this;
}
void op()
{
this->builtin_op();
}
};
int main()
{
pack p1{0xff, 0x0f, 0xf0, 0x06}, p2{0x0f00, 0xf000, 0x6700, 0xff00};
pack p3{0x12340000, 0x56780000, 0x45120000, 0xdead0000};
p3.apply ( [] ( long i, long j, long k )->long{return i | j | k;}, p1, p2, p3 );
p3.op();
return 0;
}
该代码编译错误:
main.cpp:17:24: error: cannot cast 'pack' to its private base class 'builtin_pack'
v[i] = f ( t.v[i]... );
^
main.cpp:29:15: note: in instantiation of function template specialization 'builtin_pack::builtin_apply<(lambda
at main.cpp:42:16), pack, pack, pack>' requested here
this->builtin_apply ( f, t... );
^
main.cpp:42:8: note: in instantiation of function template specialization 'pack::apply<(lambda at
main.cpp:42:16), pack, pack, pack>' requested here
p3.apply ( [] ( long i, long j, long k )->long{return i | j | k;}, p1, p2, p3 );
^
main.cpp:22:14: note: implicitly declared private here
class pack : builtin_pack
^~~~~~~~~~~~
main.cpp:17:26: error: 'v' is a private member of 'builtin_pack'
v[i] = f ( t.v[i]... );
^
main.cpp:22:14: note: constrained by implicitly private inheritance here
class pack : builtin_pack
^~~~~~~~~~~~
main.cpp:5:10: note: member is declared here
long v[4];
^
2 errors generated.
我想要做的是使用自定义(lambda)函数(称为&#39; apply&#39;)实现映射方法。当私有实现者 - 公共包装器的层次结构不存在时,它很容易工作,所以当数组v
只在类pack
中时,它会按预期编译并运行。但是,当数据存储在私有继承的类中时,它不起作用。
类的结构是一个私有的实现者类以及一个包装类,在中间我遇到了这个错误。
我是否以错误的方式使用了可变参数模板?或者有可用的解决方法吗?
(很抱歉我表达不好,因为我是C ++和stackoverflow的新手以及非英语母语人士,只要保留原意,欢迎修改或提出问题!)
答案 0 :(得分:4)
您的问题是,对于私有继承,您无法从pack*
转换为builtin_pack*
(在pack
之外,即)。如果你投了它,代码会编译,虽然我不确定这是不是你所追求的:
template<typename Func, typename... Targs>
pack& apply ( Func f, Targs ... t )
{
this->builtin_apply ( f, static_cast<builtin_pack&&>(t)... );
return *this;
}