Я намереваюсь использовать 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"});
}
Это просто недосмотр с моей стороны или ошибка?
std::make_shared
. - person GManNickG   schedule 27.04.2011make_shared
наspnew
в моем примере, он все равно терпит неудачу для случаяfails
с эквивалентными ошибками. Так что теперь, по крайней мере, я знаю, где не ошибка ... - person Jon Purdy   schedule 27.04.2011