gpt4 book ai didi

c++ - 格式错误的 C++0x 代码或编译器错误?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:44:34 24 4
gpt4 key购买 nike

在下面的 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) 的一部分通过以下方式解决两个克隆函数模板之间可能存在的歧义偏序 w.r.t.第二个函数参数。

不幸的是,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* 代码会编译,因为在这种情况下重载解析更喜欢第一个函数模板。但这违背了将表达式作为函数声明的一部分的目的。目的是让编译器在发生错误时将该函数踢出重载决议集。

最佳答案

我在使用 MSVC 时遇到了一个非常相似的问题,结果是编译器无法识别我在虚函数中的协变返回类型。尝试将 derived 的克隆定义更改为返回 abc

关于c++ - 格式错误的 C++0x 代码或编译器错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4827531/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com