在以下 C++0x 代码中,我尝试通过使用克隆成员函数(如果存在)来克隆对象并使用复制构造函数:
struct use_copy_ctor {};
struct prefer_clone_func : use_copy_ctor {};
template<class T>
auto clone(T const* ptr, prefer_clone_func)
-> decltype(ptr->clone())
{ return ptr->clone(); }
template<class T>
auto clone(T const* ptr, use_copy_ctor)
-> decltype(new T(*ptr))
{ return new T(*ptr); }
struct abc {
virtual ~abc() {}
virtual abc* clone() const =0;
};
struct derived : abc
{
derived* clone() const { return new derived(*this); }
};
int main()
{
derived d;
abc* p = &d;
abc* q = clone(p,prefer_clone_func());
delete q;
}
这个想法是使用 auto...->decltype(expr) 来清除格式错误的表达式,作为模板参数推导 (SFINAE) 的一部分,并通过第二个函数的部分排序来解决两个克隆函数模板之间可能存在的歧义范围。
不幸的是,GCC 4.5.1 不接受这个程序:
test.cpp: In function 'int main()':
test.cpp:28:39: error: cannot allocate an object of abstract type
'abc'
test.cpp:14:12: note: because the following virtual functions are
pure within 'abc':
test.cpp:16:16: note: virtual abc* abc::clone() const
test.cpp:28:39: error: cannot allocate an object of abstract type
'abc'
test.cpp:14:12: note: since type 'abc' has pure virtual functions
现在,问题是,这是一个编译器错误还是我错误地认为 SFINAE 在这里适用?我会很感激一个有充分理由的答案。
编辑:
如果我因为重载解析而更改decltype(new T(*ptr))
代码T*
编译,在这种情况下更喜欢第一个函数模板。但这违背了将表达式作为函数声明的一部分的目的。目的是让编译器在发生错误时将函数踢出重载决议集。