【发布时间】:2014-12-22 13:38:36
【问题描述】:
我有一个可以使用operator<< 写入对象的类层次结构。示例如下:
#include <iostream>
struct Base
{
};
struct Derived : public Base
{
};
struct Shift
{
template< typename U >
Shift& operator<<(const U&)
{
std::cerr << __PRETTY_FUNCTION__ << std::endl;
return *this;
}
Shift& operator<<(const Base&)
{
std::cerr << __PRETTY_FUNCTION__ << std::endl;
return *this;
}
#if 0
Shift& operator<<(const Derived&)
{
std::cerr << __PRETTY_FUNCTION__ << std::endl;
return *this;
}
#endif
};
int main()
{
Shift sh;
Base bas;
Derived der;
int u32 = 0;
sh << bas;
sh << der;
sh << u32;
}
这会产生以下输出:
Shift& Shift::operator<<(const Base&)
Shift& Shift::operator<<(const U&) [with U = Derived]
Shift& Shift::operator<<(const U&) [with U = int]
如果我取消注释 #if 0 部分,它将更改为所需的输出:
Shift& Shift::operator<<(const Base&)
Shift& Shift::operator<<(const Derived&)
Shift& Shift::operator<<(const U&) [with U = int]
我有很多派生类(实际上是一个完整的层次结构),直到现在我必须为所有这些类型编写一个单独的 operator<< 定义。我想要的是有一个解决方案,其中基类型的运算符对从Base 派生的所有类型调用。这可能吗?
P.S.:我尝试了几种解决方案,例如编写一个辅助类:
struct Base
{
};
struct Derived : public Base
{
};
template< typename T >
struct Helper
{
static void shift()
{
std::cerr << __PRETTY_FUNCTION__ << std::endl;
}
};
template< >
struct Helper< Base >
{
static void shift()
{
std::cerr << __PRETTY_FUNCTION__ << std::endl;
}
};
struct Shift
{
template< typename U >
Shift& operator<<(const U& value)
{
Helper< U >::shift();
return *this;
}
};
输出:
static void Helper<Base>::shift()
static void Helper<T>::shift() [with T = Derived]
static void Helper<T>::shift() [with T = int]
但仍然调用基本模板,而不是 Base 特化。
P.P.S.:不幸的是,我目前仅限于C++03 没有Boost。
【问题讨论】:
标签: c++ templates overloading template-specialization c++03