【发布时间】:2011-12-15 10:07:52
【问题描述】:
这是我检查类是否有成员函数begin 的代码:
template<typename T> struct has_begin
{
struct dummy {typedef void const_iterator;};
typedef typename std::conditional< has_iterator<T>::yes, T, dummy>::type TType;
typedef typename TType::const_iterator Iter;
struct fallBack{ Iter begin() const ; Iter end() const;};
struct checker : T, fallBack {};
template <typename B, B> struct cht;
template<typename C> static char check(cht< Iter (fallBack::*)() const, &C::begin>*); // problem is here
template<typename C> static char (&check(...))[2];
public:
enum {no = (sizeof(check<checker>(0))==sizeof(char)),
yes=!no};
};
如果我将check(cht< Iter (fallBack::*)() const, &C::begin>*); 中cht 的第二个参数更改为
&checker::begin ,这不会改变代码的语义,因为 cht 的第二个模板参数总是 checker 由于 enum {no = (sizeof(check<checker>(0))==sizeof(char))
但代码更改导致 error 现在是:
prog.cpp: In instantiation of 'has_begin<std::vector<int> >':
prog.cpp:31:51: instantiated from here
prog.cpp:23:38: error: reference to 'has_begin<std::vector<int> >::checker::begin' is ambiguous
我想知道这种行为背后的原因。
【问题讨论】:
-
您的结构非常复杂。它应该做什么?看起来像检查类 T 是否有一个名为 begin 的成员函数
-
@VJovic 你说得对,我编辑了 Q 的第一行 :)
-
如果进行更改会出现什么错误?
-
@AlanStokes 模糊调用错误 :(
-
@Freak 枚举:
What error do you get表示Please post the error message you get verbatim (copy+paste)。