Niklas R
Niklas R

Reputation: 16870

static non-template method in template class

I want to add a static function to a template class that is accessible without passing template parameters first. Is that possible?

namespace foo {
  template <typename T>
  class bar {
  public:
    static void eggs();
  };
}

foo::bar<some_t>::eggs();  // works
foo::bar::eggs();  // does not work

I would like to avoid moving eggs() to the foo namespace or to create a new namespace for it (eg. foo::bar_::eggs(), ugh).

Upvotes: 1

Views: 1512

Answers (4)

Francis Cugler
Francis Cugler

Reputation: 7905

After experimenting with your code:

I want to add a static function to a template class that is accessible without passing template parameters first. Is that possible?

namespace foo {
  template <typename T>
  class bar {
  public:
    static void eggs();
  };
}

foo::bar<some_t>::eggs();  // works
foo::bar::eggs();  // does not work

I would like to avoid moving eggs() to the foo namespace or to create a new namespace for it (eg. foo::bar_::eggs(), ugh).

I have come to the conclusion that, the first instance of

foo::bar<some_t>::eggs(); // works while
foo::bar::eggs(); // doesn't 

Is due to the fact that when working with templates, anything within the class has to be relative to a specific object, even if you do not want the function to be. I even tried using function pointers and tried to save them to template class and without no avail I couldn't even get that to compile. I do not see much of an option for you in this situation. There maybe other tricks out there that someone might know, but not from what I can see.

Upvotes: 1

bolov
bolov

Reputation: 75697

You can make the template parameter optional and you can define a specialized template. Like this:

namespace foo {

template <typename T = void> class bar {
public:
  static void eggs() { cout << "First there was the egg" << endl; }
};

template <> class bar<void> {
public:
  static void eggs() {
    cout << "Then there was the chicken... or was it?" << endl;
  }
};
}

auto main() -> int {
  foo::bar<int>::eggs(); // egg
  foo::bar<>::eggs();    // chicken

  return 0;
}

Upvotes: 0

Paulo1205
Paulo1205

Reputation: 944

Remember that foo::bar does not name any type, but solely a template that can be used to create other types.

Besides using typedefs/type aliases (through using), you can perhaps have a non-templated base class for you templates, and then put your static members there. If you use public inheritance, changing the static member in any of the templated classes will change in all of them.

Upvotes: 1

Edward Strange
Edward Strange

Reputation: 40859

No. That is not how template classes work. What you want to do is not possible in C++.

Upvotes: 6

Related Questions