假设我有一系列带有私有构造函数的类,必须通过专用New(...)
静态函数分配,如下所示:
class Foo {
public:
static Foo* New();
private:
Foo() {}
};
class Bar {
public:
static Bar* New(int a, int b);
private:
Bar() {}
};
我想编写一个模板类,以通用的方式调用它们的New(...)
静态函数:
template<class T, typename... Args>
class Test {
public:
static Test<T> Make(Args&&... args) {
return Test<T>(T::New(std::forward<Args>(args)...));
}
private:
inline Test(T* object) : m_object(object) {}
T* m_object;
};
所以我可以这样做:
auto foo = Test<Foo>::Make();
auto bar = Test<Bar>::Make(1, 2);
没有参数的Foo
案例有效,但不是Bar
案例。 Clang说,它希望New()
不带参数,好像参数没有正确转发一样。我做错了什么?
更新:在尝试拨打Buffer
时,Clang和我的Test<Buffer>::Make(1000)
课程发生了真实的错误:
Buffer.hpp:25:29: note: candidate function template not viable: requires single argument 'string', but no arguments were provided
inline static BufferRef New(const char (&string)[N]) { // For literal strings
^
Buffer.hpp:16:29: note: candidate function not viable: requires single argument 'length', but no arguments were provided
inline static BufferRef New(size_t length) {
^
Buffer.hpp:29:29: note: candidate function not viable: requires at least argument 'string', but no arguments were provided
inline static BufferRef New(const char* string, bool copy = true) {
^
Buffer.hpp:33:29: note: candidate function not viable: requires at least argument 'string', but no arguments were provided
inline static BufferRef New(const std::string& string, bool copy = true) {
^
Buffer.hpp:20:29: note: candidate function not viable: requires at least 2 arguments, but 0 were provided
inline static BufferRef New(void* bytes, size_t length, bool copy = true) {
答案 0 :(得分:1)
我想通了 - 可变参数模板参数&#34;显然&#34;需要在静态函数上,而不是类本身:
template<class T>
class Test {
public:
template<typename... Args>
static Test<T> Make(Args&&... args) {
return Test<T>(T::New(std::forward<Args>(args)...));
}
private:
inline Test(T* object) : m_object(object) {}
T* m_object;
};