作为模板参数的常量
我有两个结构:
// ----- non-const -----
struct arg_adapter
{
EArgType type; // fmtA, fmtB, ...
union
{
TypeA * valueA;
TypeB * valueB;
// ... more types
}
arg_adapter(TypeA & value) : type(fmtA), valueA(&value) {}
arg_adapter(TypeB & value) : type(fmtB), valueB(&value) {}
// ...
}
// ----- const version -----
struct const_arg_adapter
{
EArgType type; // fmtA, fmtB, ...
union
{
TypeA const * valueA;
TypeB const * valueB;
// ... more types
}
arg_adapter(TypeA const & value) : type(fmtA), valueA(&value) {}
arg_adapter(TypeB const & value) : type(fmtB), valueB(&value) {}
// ...
}
它们应该在诸如以下的方法中使用:
Convert(const_arg_adapter from, arg_adapter to)
有多个 TypeX'(大约 5 个,可能会更多),其中大多数是原始的。这是为了避免维护不同的原型。
现在我的问题;-)
有没有办法使常量成为模板参数? 我的目标是只维护一个结构,即
template <Qualifier CONSTNESS>
struct arg_adapter_t
{
...
CONSTNESS TypeA * valueA;
...
}
I have two structs:
// ----- non-const -----
struct arg_adapter
{
EArgType type; // fmtA, fmtB, ...
union
{
TypeA * valueA;
TypeB * valueB;
// ... more types
}
arg_adapter(TypeA & value) : type(fmtA), valueA(&value) {}
arg_adapter(TypeB & value) : type(fmtB), valueB(&value) {}
// ...
}
// ----- const version -----
struct const_arg_adapter
{
EArgType type; // fmtA, fmtB, ...
union
{
TypeA const * valueA;
TypeB const * valueB;
// ... more types
}
arg_adapter(TypeA const & value) : type(fmtA), valueA(&value) {}
arg_adapter(TypeB const & value) : type(fmtB), valueB(&value) {}
// ...
}
They are supposed to be used in methods such as:
Convert(const_arg_adapter from, arg_adapter to)
There are multiple TypeX' (about 5, may become more), most of them primitive. This is to avoid maintaining different prototypes.
Now my question ;-)
Is there a way to make the const-ness a template parameter?
My goal is to maintain only one struct, i.e.
template <Qualifier CONSTNESS>
struct arg_adapter_t
{
...
CONSTNESS TypeA * valueA;
...
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使其接受 元函数您可以应用任何您喜欢的转换
或接受 元函数类以获得更大的灵活性(包括使
F
具有您的arg_adapter
等不知道的默认参数的能力。You can make it accept a metafunction and you can apply any transformation you like
Or accept a metafunction class to get more flexibility (including the ability to make
F
have default arguments not known to yourarg_adapter
and such.我只是偶然发现了一种更好的方法,使用 Alexandrescu 在“现代 C++ 设计”中提出的类型选择思想:
这是类型选择器:
然后你的类将如下所示:
为了方便起见,你可以使用 typedefs:
这是我的旧答案简单类型特征:
I just stumbled about an even better way using the type selection ideom presentend by Alexandrescu in "Modern C++ Design":
This is the type selector:
Your class would then look like this:
You can use typedefs for convenience:
This was my old answer using simple type traits:
也许我没明白,但为什么不能使用
Declare a typedef 来简化工作
Maybe I didn't get it, but why can't you use
Declare a typedef to simplify the job