在运行时选择 ctor 参数
是否可以解决以下使用 mpl 在运行时选择参数的场景?
struct A {
A(int number) { /* use number */ } };
struct B { };
template <typename T, int n>
struct A_or_B_Holder {
A_or_B_Holder() : _t( /* void or 'n', depends on T */ ) { }
private:
T _t;
};
A_or_B_Holder<B, void> b;
A_or_B_Holder<A, 3> a;
理想情况下,
A_or_B_Holder<B> b;
A_or_B_Holder<A, 3> a;
Is it possible to address the following scenario of choosing the argument at runtime with mpl?
struct A {
A(int number) { /* use number */ } };
struct B { };
template <typename T, int n>
struct A_or_B_Holder {
A_or_B_Holder() : _t( /* void or 'n', depends on T */ ) { }
private:
T _t;
};
A_or_B_Holder<B, void> b;
A_or_B_Holder<A, 3> a;
Ideally,
A_or_B_Holder<B> b;
A_or_B_Holder<A, 3> a;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的第一个问题是
void
是一种类型,而不是整数。您可以使模板接受两种类型,第二种是boost::mpl::int_
或void
。然后,您可以专门化整个结构,也可以将数据成员放入基类中并对其进行专门化。
更自然的可能是不要求参数是编译时常量(因为无论如何您都将编译时常量转换为运行时变量)。只需重载构造函数即可。
Your first problem is that
void
is a type, not an integer. You could make the template accept two types, the second being eitherboost::mpl::int_
orvoid
.Then you could either specialize the entire struct, or you could put the data member in a base class and specialize that.
More natural might be not to require the parameter to be a compile-time constant (as you are turning the compile-time constant into a run-time variable anyway). Just overload the constructor.
您可以使用
Boost.Variant
< /a>如果您对它的实现方式更感兴趣,而不是您可以使用什么,我建议您查看
Boost.Any
和Boost.Variant
。You could use a
Boost.Variant
If you are more interested in how this is implemented, rather than what you can use, I suggest you check out the implementations of
Boost.Any
andBoost.Variant
.我认为在运行时传递不同的参数是不可能的。您必须拥有所有 T 类型都具有的标准构造函数。您可以从 std::vector构造所有 T 类型,并使用它来传递可变数量的变量类型参数,但这是超级危险的。
但是,您的示例似乎实际上是在编译时而不是运行时决定的,这是可以解决的。
I think that passing different arguments at run time is impossible. You'll have to have a standard constructor that all T types will have. You can make all T types construct from
std::vector<void*>
and use that to pass a variable number of variable type arguments, but that's super dangerous.However, your sample seems to actually be deciding at compile-time, not run-time, which is solvable.