【发布时间】:2015-01-05 10:57:51
【问题描述】:
我正在试用 Sean Parent 在 GoingNative 2013 演讲中提供的代码 - "Inheritance is the base class of evil".(上一张幻灯片中的代码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 的 draw 全局函数更改为完整的模板特化,则代码可以编译并正常工作。
我得到的错误信息如下,之后是一堆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 函数重载?是因为模板引用是贪婪的吗?如何解决这个问题?
【问题讨论】:
-
我用 MSVC13 尝试了你的代码,它编译得很好,在第一种情况下使用 int 版本,在第二种情况下使用 MyClass 版本。您应该添加有关您正在使用的编译器的信息
-
我使用 clang --version clang version 3.5.0 (tags/RELEASE_350/final)。
标签: c++ templates inheritance language-lawyer argument-dependent-lookup