我打算用shared_ptr
颇有几分在即将开展的项目,所以(没有意识到std::make_shared
)我想写一个可变参数模板功能spnew<T>(...)
为shared_ptr
-returning待机为new
。一切都很顺利,直到我试图使用构造函数包含initializer_list
的类型。我从GCC 4.5.2以下,当我尝试编译下面的小例子:扩大参数包含initializer_list同构造函数
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'。 – GManNickG 2011-04-27 02:18:18
@GMan:是的,我发现并将使用它,但我仍然好奇我写的是什么。 – 2011-04-27 02:20:11
@GMan:实际上,在我的例子中,尝试用'make_shared'代替'spnew',它仍然失败,出现了同样错误的'failed'情况。所以,现在至少我知道错误不在哪里... – 2011-04-27 02:22:56