0

我想要类似以下(psuedo-C++)类的东西。基本思想是将任何新值初始化为最后设置的值。

粘性数据.hpp

template<typename T>
class StickyData {
  static T s_lastValue;
  T m_value;
  StickyData() { m_value = s_lastValue; } // Initialize to last set value
  T& operator = (T& rhs)  { 
       m_value = s_lastValue = rhs;
  }
}

template<> StickyData<T>::s_lastValue;

使用数据.cpp

typedef int Ford;
typedef int GM;
typedef int Toyota;

StickyData<Ford> aFord;
StickyData<GM> aGM;
StickyData<Toyota> aToyota;

aFord = 10;
aGM = 2
aToyota = 20;

StickyData<Ford> anotherFord; // I want this automatically initialized to 10

为此,我需要对这些 typedef 中的每一个进行独特的 StickyData 编译。我实际上认为这会按原样工作,但是当我运行此代码时,我似乎只为所有这些不同的模板实例创建了 1 个静态 int。

我可以以某种方式为相同的基础值类型强制一个新的模板编译吗?

4

1 回答 1

2

在您的示例代码中,福特、通用汽车和丰田汽车都是同一类型。您应该将它们声明为实际的单独类型:

struct Toyota {};
struct Ford   {};
struct GM     {};

目前,您的代码相当于:

HoldData<int> aFord;
HoldData<int> aGM;
HoldData<int> aToyota;

这是我上面建议的完整实现:

#include <iostream>

template<typename Hash, typename Value>
struct StickyData {
        static Value s_lastValue;
        Value m_value;
        StickyData(): m_value(s_lastValue) {}

        StickyData<Hash, Value> & operator=(Value const & rhs) {
                m_value = s_lastValue = rhs;
                return *this;
        }
};

struct GM {};
struct Ford {};
struct Honda {};

template <typename Hash, typename Value> Value StickyData<Hash, Value>::s_lastValue = 0;

int main() {
        StickyData<GM, int> aGM;
        StickyData<Ford, int> aFord;
        StickyData<Honda, double> aHonda;

        aGM = 3;
        aFord = 4;
        aHonda = 7.89;

        std::cout << "aGM:    " << aGM.m_value << "\n";
        std::cout << "aFord:  " << aFord.m_value << "\n";
        std::cout << "aHonda: " << aHonda.m_value << "\n";
        std::cout << "\n";

        StickyData<GM, int> aNewGM;
        std::cout << "aNewGM: " << aGM.m_value << "\n";
}

这将输出:

aGM:    3
aFord:  4
aHonda: 7.89

aNewGM: 3

回应评论: “......但是编译器确实知道区别,例如,如果你有 typedef 的参数,你可以标记一些明确的东西,然后不接受类型'int'作为参数...... ”

我有以下代码:

typedef int foo;

class C {
    explicit C(int x);
    explicit C(foo x);
};

此代码无法编译并出现以下错误:

blah.cc:5:11: error: ‘C::C(foo)’ cannot be overloaded
  explicit C(foo x);
           ^
blah.cc:4:11: error: with ‘C::C(int)’
  explicit C(int x);
           ^
于 2013-09-17T13:46:51.650 回答