Я собираюсь использовать shared_ptr
в следующем проекте немного, поэтому (не зная std::make_shared
) я хотел написать функцию шаблона переменной spnew<T>(...)
в качестве shared_ptr
-обмена new
. Все шло гладко, пока я не попытался использовать тип, конструктор которого включает initializer_list
. Я получаю следующее от GCC 4.5.2, когда пытаюсь скомпилировать минимальный пример ниже:
In function 'int main(int, char**)':
too many arguments to function 'std::shared_ptr spnew(Args ...) [with T = Example, Args = {}]'
In function 'std::shared_ptr spnew(Args ...) [with T = Example, Args = {}]':
no matching function for call to 'Example::Example()'
Как ни странно, я получаю эквивалентные ошибки, если заменяю std::make_shared
на spnew
. В любом случае, кажется, что неправильно выводить параметры, когда задействован initializer_list
, ошибочно трактуя Args...
как пустой. Вот пример:
#include <memory>
#include <string>
#include <vector>
struct Example {
// This constructor plays nice.
Example(const char* t, const char* c) :
title(t), contents(1, c) {}
// This one does not.
Example(const char* t, std::initializer_list<const char*> c) :
title(t), contents(c.begin(), c.end()) {}
std::string title;
std::vector<std::string> contents;
};
// This ought to be trivial.
template<class T, class... Args>
std::shared_ptr<T> spnew(Args... args) {
return std::shared_ptr<T>(new T(args...));
}
// And here are the test cases, which don't interfere with one another.
int main(int argc, char** argv) {
auto succeeds = spnew<Example>("foo", "bar");
auto fails = spnew<Example>("foo", {"bar"});
}
Это просто упущение с моей стороны или ошибка?