0

I have the following template function:

template<typename T>
T test_function(T arg) {return arg;}

I can create a specialized version of this for integers with:

template<>
int test_function(int arg) {return arg;}

This is practical if I use this function with integers a lot. So I can call it with:

test_function(some_integer);      // easy!
test_function<int>(some_integer); // not necessary all the time.

Now I have the following class:

template<typename T>
class Foo
{
public:
  Foo();
};

I want to be able to call it with:

Foo foo1;       // how do I do this?
Foo<int> foo2;  // I don't want to use this all the time.

How can I define this class in order to be able to create an instance of it without using angle brackets at all? Shouldn't be too hard I think, but I couldn't figure it out so far...

donald
  • 170
  • 4

2 Answers2

2

You should either use default argument (int) and then:

template<typename T = int> class Foo {};
Foo<> foo2;

or make an alias:

using MyFoo = Foo<int>; //or just Foo<> if using default argument
MyFoo foo1;

I believe you cannot create an object of templated class without indicating that it is a template class even when all template arguments have defaults.

NOTE: using is C++11 keyword, use typedef for legacy code/compilers.

Resurrection
  • 3,916
  • 2
  • 34
  • 56
  • Hmm ok, I did it like this so far. The reason I'd prefer it to have without brackets is to make the use of this class easier. Thanks for the alias hint, I think I'll go with this if there is no other solution. – donald Apr 08 '16 at 06:56
  • @donald It's the standard way of doing this. `using` is actually really nice and it exists primarily for this purpose. Its syntax is also better and more consistent than `typedef` and can be nested within a class: `class A { public: using B = SomeClass; }` and then `A::B` is a valid type (alias to `SomeClass`). – Resurrection Apr 08 '16 at 06:59
  • It's worth noting that `typedef` is by all means equivalent to corresponding `using` declaration, in particular it can also be nested within a class. – Anton Savin Apr 08 '16 at 18:09
0
template<typename T>
T test_function(T arg) {return arg;}

template<>
int test_function<int>(int arg) {return arg;}
Andrei R.
  • 2,374
  • 1
  • 13
  • 27
  • Yes, this works too for the function example, but how can I do it for the class? – donald Apr 08 '16 at 06:52
  • class functions can be specialized outside class like this: `template<> MyClass::MyClass() { /*constructor, specific for int*/}` – Andrei R. Apr 08 '16 at 06:57