tengo la intención de utilizar shared_ptr
un poco en un próximo proyecto, por lo que (no ser consciente de std::make_shared
) que quería escribir una función de plantilla variadic spnew<T>(...)
como shared_ptr
-Volviendo en stand-para new
. Todo fue bien hasta que intenté usar un tipo cuyo constructor incluye un initializer_list
. Me sale el siguiente GCC 4.5.2 desde cuando intento compilar el ejemplo mínima a continuación:La expansión paquete de parámetro que contiene initializer_list al constructor
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()'
Por extraño que parezca, tengo errores equivalentes si sustituyo std::make_shared
para spnew
. En cualquier caso, parece deducir los parámetros incorrectamente cuando se trata de initializer_list
, tratando erróneamente Args...
como vacío. Aquí está el ejemplo:
#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"});
}
¿Esto es solo un descuido de mi parte o un error?
Hay 'std :: make_shared', por cierto. – GManNickG
@GMan: Sí, lo he encontrado y lo usaré, pero todavía tengo curiosidad por saber qué hay con lo que escribí. –
@GMan: en realidad, vengo a intentar sustituir 'make_shared' por' spnew' en mi ejemplo, aún falla para el caso 'failed' con errores equivalentes. Así que ahora al menos sé dónde no está el error ... –