我正在尝试Sean Parent在GoingNative 2013上的演讲中提供的代码 - “继承是邪恶的基础”。 (上一张幻灯片中的代码可用于 https://gist.github.com/berkus/7041546
我试图自己实现相同的目标,但我无法理解为什么下面的代码不会按照我的预期行事。
#include <boost/smart_ptr.hpp>
#include <iostream>
#include <ostream>
template <typename T>
void draw(const T& t, std::ostream& out)
{
std::cout << "Template version" << '\n';
out << t << '\n';
}
class object_t
{
public:
template <typename T>
explicit object_t (T rhs) : self(new model<T>(rhs)) {};
friend void draw(const object_t& obj, std::ostream& out)
{
obj.self->draw(out);
}
private:
struct concept_t
{
virtual ~concept_t() {};
virtual void draw(std::ostream&) const = 0;
};
template <typename T>
struct model : concept_t
{
model(T rhs) : data(rhs) {};
void draw(std::ostream& out) const
{
::draw(data, out);
}
T data;
};
boost::scoped_ptr<concept_t> self;
};
class MyClass {};
void draw(const MyClass&, std::ostream& out)
{
std::cout << "MyClass version" << '\n';
out << "MyClass" << '\n';
}
int main()
{
object_t first(1);
draw(first, std::cout);
const object_t second((MyClass()));
draw(second, std::cout);
return 0;
}
此版本处理打印 int
很好,但在第二种情况下无法编译,因为编译器不知道如何使用 MyClass
同 operator<<
。我无法理解为什么编译器不会选择专门为其提供的第二个重载 MyClass
。如果我更改model :: draw()方法的名称并删除,则代码编译并正常工作 ::
来自其主体的全局命名空间说明符,或者如果我将MyClass'绘制全局函数更改为完整的模板特化。
我得到的错误信息如下,之后是一堆 candidate function not viable...
t76_stack_friend_fcn_visibility.cpp:9:9: error: invalid operands to binary expression ('std::ostream' (aka 'basic_ostream<char>') and 'const MyClass')
out << t << '\n';
~~~ ^ ~
t76_stack_friend_fcn_visibility.cpp:36:15: note: in instantiation of function template specialization 'draw<MyClass>' requested here
::draw(data, out);
^
t76_stack_friend_fcn_visibility.cpp:33:9: note: in instantiation of member function 'object_t::model<MyClass>::draw' requested here
model(T rhs) : data(rhs) {};
^
t76_stack_friend_fcn_visibility.cpp:16:42: note: in instantiation of member function 'object_t::model<MyClass>::model' requested here
explicit object_t (T rhs) : self(new model<T>(rhs)) {};
^
t76_stack_friend_fcn_visibility.cpp:58:20: note: in instantiation of function template specialization 'object_t::object_t<MyClass>' requested here
const object_t second((MyClass()));
^
为什么全局绘图模板函数的模板版本选择MyClass函数重载?是因为模板参考是贪婪的吗?如何解决这个问题?