[英]Eliminate repetition in C++ code?
鑒於以下內容:
StreamLogger& operator<<(const char* s) {
elements.push_back(String(s));
return *this;
}
StreamLogger& operator<<(int val) {
elements.push_back(String(asString<int>(val)));
return *this;
}
StreamLogger& operator<<(unsigned val) {
elements.push_back(String(asString<unsigned>(val)));
return *this;
}
StreamLogger& operator<<(size_t val) {
elements.push_back(String(asString<size_t>(val)));
return *this;
}
有沒有辦法消除重復? 我想使用模板,但我只想要它用於以下類型:const char * int,unsigned和size_t
實際上,在“vanilla”C ++中,您可以手動編寫特定類型,也可以使用dirkgently建議的模板。
也就是說,如果你可以使用Boost,你可以做到你想要的:
template <class T>
StreamLogger& operator<<(T val)
{
typedef boost::mpl::vector<const char*, int,
unsigned, size_t> allowed_types;
BOOST_MPL_ASSERT_MSG(boost::mpl::contains<allowed_types, T>::value,
TYPE_NOT_ALLOWED, allowed_types);
// generic implementation follows
elements.push_back(boost::lexical_cast<std::string>(val));
return *this;
}
如果正在編譯的類型未包含在類型TYPE_NOT_ALLOWED
中,這將生成編譯時錯誤,其中嵌入了消息TYPE_NOT_ALLOWED
。
此外,由於這個答案需要Boost,我只使用了lexical_cast
。 你會注意到你正在重復那段代碼,這很糟糕。 考慮將該功能包裝到一個函數中。
如果您無法使用Boost,您可以使用某些類型特征輕松模擬這個:
template <typename T, typename U>
struct is_same
{
static const bool value = false;
};
template <typename T>
struct is_same<T, T>
{
static const bool value = true;
};
template <bool>
struct static_assert;
template <>
struct static_assert<true> {}; // only true is defined
// not the best, but it works
#define STATIC_ASSERT(x) static_assert< (x) > _static_assert_
template <class T>
StreamLogger& operator<<(T val)
{
STATIC_ASSERT(is_same<const char*, T>::value ||
is_same<int, T>::value ||
is_same<unsigned, T>::value ||
is_same<size_t, T>::value);
// generic implementation follows
elements.push_back(boost::lexical_cast<std::string>(val));
return *this;
}
如果斷言失敗,這也會產生編譯時錯誤,盡管代碼不那么性感。 :( < - 不性感
這樣的事情應該有效:
template <class T>
StreamLogger& operator<<(T val) {
istringstream s;
s << val;
elements.push_back(s.str()); // assuming elements is a vector<string>
return *this;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.