这种容器实现完全合理吗?
您是否可以以其他方式编写以下简单容器,或者它是完全合理的:
template <typename T, bool small_>
struct TransType
{
typedef const T& param_type;
};
template <typename T>
struct TransType<T, true>
{
typedef const T param_type;
};
template <class T>
class Container:public TransType<T,sizeof(T)<=sizeof(void*)> {
public:
param_type getVal(){
return obj;
}
void setVal(param_type input){
containment=input;
}
private:
T containment;
};
Would you write the following simple container any other way or it's totally sensible as it is:
template <typename T, bool small_>
struct TransType
{
typedef const T& param_type;
};
template <typename T>
struct TransType<T, true>
{
typedef const T param_type;
};
template <class T>
class Container:public TransType<T,sizeof(T)<=sizeof(void*)> {
public:
param_type getVal(){
return obj;
}
void setVal(param_type input){
containment=input;
}
private:
T containment;
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
查看 Boost.CallTraits。即,
boost::call_traits::param_type
。您不需要客户端指定类型是否小,这是元函数的工作。也没有真正需要继承任何东西。
事实上,您现在的代码格式不正确。由于 param_type 不是依赖类型,因此查找时不考虑基类;并且不会被发现。您需要使用基类显式限定它,添加 using 指令,或者重新 typedef 它。
您只想最终得到:
通过:
现在条件是自动的,并且没有基类麻烦。
Look into Boost.CallTraits. Namely,
boost::call_traits<T>::param_type
.You shouldn't need the client to specify whether the type is small or not, that's the metafunction's job. Nor is there really a need to inherit from anything.
In fact your code right now is ill-formed. Because
param_type
isn't a dependent type, the lookup is done without taking into consideration the base class; and will not be found. You'd need to either explicitly qualify it with the base class, add a using-directive, or re-typedef it.You just want to end up with:
By:
Now the condition is automatic, and there's no base class hassle.
我不会继承元函数。
I wouldn't inherit from the metafunction.
除了 GMan 关于需要一种或另一种形式的显式析构函数的评论之外,增加的复杂性是否会为您带来显着的性能?标准库似乎认为用户应该在容器中存储适当的类型,这样在某些情况下复制就不会成为瓶颈。
Aside from GMan's comment about needing an explicit destructor in one form or another, does the added complexity gain you significant performance? The standard library seemed to think that it was up to the user to store an appropriate type in the container such that copying in some cases wasn't a bottleneck.