我希望得到类似以下(psuedo-C ++)类的内容。基本思路是将任何新值初始化为最后一个设定值。
StickyData.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;
UseData.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。
我是否可以针对相同的基础值类型以某种方式强制执行新模板编译?
答案 0 :(得分:2)
在您的示例代码中,Fords,GM和Toyotas都是相同的类型。您应该将它们声明为实际的单独类型:
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'ed参数,你可以标记一些明确的东西然后不接受类型'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);
^