Вопрос

I want to be able to specialize the ctor of a class the following way:

template<typename T>
class Foo {
public:
  template<typename... Ts>
  Foo(Ts... & args) {
    // ...
  }

  template<>
  Foo(int i) {
    // ...
  }
};

I get the following error:

error: explicit specialization in non-namespace scope ‘class Foo’

If I try to move the specialization outside the class, like this:

template<typename T>
class Foo {
public:
  template<typename... Ts>
  Foo(Ts &... args) {
    // ...
  }
};

template<typename T>
template<int>
Foo<T>::Foo(int i) {
    // ...
}

I get the following errors:

error: prototype for ‘Foo::Foo(int)’ does not match any in class ‘Foo’

error: candidate is: template template Foo::Foo(Ts& ...)

How do I do this correctly?

Это было полезно?

Решение

You can just overload the constructor instead:

template<typename T>
class Foo {
public:
  template<typename... Ts>
  Foo(Ts&... args) {
    // ...
  }

  // template<>  <- REMOVE THIS
  Foo(int i) {
    // ...
  }
};

Overload resolution will prefer the non-template overload so doing Foo<MyType> f(1234); would choose Foo<MyType>::Foo(int);.

LIVE EXAMPLE (I've modified the variadic to be const for it to accept temporaries for the sake of the example).

Note that the position of the type modifier in your variadic function is wrong. It should be with the type, on the left side of ...:

Foo(Ts&...  args)

Другие советы

member function and by extension constructors are not specialize-able without specializing the outer template completely.

Just write the ctor with an int not template will works here.

14.7.3p18: "In an explicit specialization declaration for a member of a class template or a member template that appears in namespace scope, the member template and some of its enclosing class templates may remain unspecialized, except that the declaration shall not explicitly specialize a class member template if its enclosing class templates are not explicitly specialized as well."

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top