dimanche 3 janvier 2016

Calling a static function on a parameter class in a template while forwarding arguments

Say I have a series of classes with private constructors and which must be allocated through dedicated New(...) static functions like this:

class Foo {
public:
  static Foo* New();
private:
  Foo() {}
};

class Bar {
public:
  static Bar* New(int a, int b);
private:
  Bar() {}
};

I want to write a template class to call their New(...) static functions in a generic way:

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;
};

So that I can do:

auto foo = Test<Foo>::Make();
auto bar = Test<Bar>::Make(1, 2);

The Foo case without arguments work, but not the Bar case. Clang says that it expects New() to take no arguments as if the arguments were not forwarded correctly. What am I doing wrong?

UPDATE: Here's a real-life error from Clang with my Buffer class when attempting to call 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) {

Aucun commentaire:

Enregistrer un commentaire