xnet吧 关注:9贴子:110
  • 3回复贴,共1

突然发现有个很好的对ValueType的优化方法~

只看楼主收藏回复

忘记叫什么设计模式了,大概是这样:
struct Object
{
virtual string GetType() const { return typeid(*this).name(); }
virtual string ToString() const { return GetType(); }
virtual ~Object() { }
};
struct ValueType { };
//This makes a value type an Object.
//Specialize this template if a value
//type is implementing an interface.
template <class T>
struct RefValueType : Object, T
{
static_assert(std::is_base_of<ValueType, T>::value, "T must be value type.");
template <class...TArgs>
RefValueType(TArgs &&...args) : T(args...) { }
// Use using T::T; when mingw supports that.
virtual ~RefValueType() { }
virtual string ToString() const { return T::ToString(); }
virtual string GetType() const { return T::GetType(); }
};
struct IFormattable
{
virtual string ToString(string format) const = 0;
virtual ~IFormattable() { }
};
struct Int32 : ValueType
{
//make this struct looks like a int.
string GetType() const { return "Int32"; }
string ToString() const { /*normal tostring*/ }
//implementing IFormattable? Yes, but implicitly.
string ToString(string format) const { /*tostring w/ format*/ }
private: int value;
};
template <>
struct RefValueType<Int32> : Object, Int32, IFormattable
{
template <class...TArgs>
RefValueType(TArgs &&...args) : Int32(args...) { }
virtual string GetType() const { return Int32::GetType(); }
virtual string ToString() const { return Int32::ToString(); }
virtual string ToString(string format) const { return Int32::ToString(format); }
virtual ~RefValueType() { }
};
//When boxing a value type "vt",
//a RefValueType<decltype(vt)> is created on gc as a copy.
//This saves space for a value type object created on
//stack(you don't need a vtable -w-).


IP属地:美国1楼2011-08-30 13:37回复
    ValueType不从Object继承这个想法好像当时讨论的时候就有了
    另一个想法:ValueType从Object继承,但Int32里的所有成员函数全部声明为final(也许可以将整个Int32结构声明为final),虽然是虚函数,但因为不能再被override,所以不存在多态问题,编译器也许可以将查表一步优化掉(装包以后virtual就起到作用)


    IP属地:上海2楼2011-10-13 08:44
    回复
      Seems that cpp will optimize the call when the object is accessed by its variable name. :-D


      IP属地:美国3楼2011-10-13 10:52
      回复
        表示不懂C语言。。。只会汇编的飘过……


        IP属地:北京4楼2012-05-03 17:36
        回复