好的,我做了一些研究,显然在这个主题上有很多关于SO的重复问题,仅举几例:
但是我忍不住再提一下,因为
auto -typed返回值,我实际上是复制函数体,唯一的区别是const函数限定符.const版本和非const版本可能返回彼此完全不相容的类型.在这种情况下,斯科特迈耶斯的const_cast习语,以及"非const功能返回非const"技术都不会起作用.举个例子:
struct A {
std::vector<int> examples;
auto get() { return examples.begin(); }
auto get() const { return examples.begin(); }
}; // Do I really have to duplicate?
// My real-world code is much longer
// and there are a lot of such get()'s
Run Code Online (Sandbox Code Playgroud)
在这种特殊情况下,auto get()返回一个iteratorwhile auto get() const返回一个const_iterator,并且两个不能相互转换(我知道erase(it,it) …
我正在使用C++模板编写一个抽象工厂,并遇到了一个小障碍.即,泛型类T可以提供以下一种或多种方式来构造对象:
static T* T::create(int arg);
T(int arg);
T();
Run Code Online (Sandbox Code Playgroud)
我正在编写抽象工厂类,以便它可以按给定的顺序自动尝试这三种潜在的构造:
template <class T>
class Factory {
public:
T* create(int arg) {
return T::create(arg); // first preference
return new T(arg); // this if above does not exist
return new T; // this if above does not exist
// compiler error if none of the three is provided by class T
}
};
Run Code Online (Sandbox Code Playgroud)
如何使用C++模板实现此目的?谢谢.