How to limit a template class or function to specific types?

Aug 6, 2010 at 10:32am
Hi all, I am new here.

Just a quick question.

consider a template function prototype like this:

template <class X> void myfunc1(X &var);

or

template <class X> X* myfunc2();

etc.

Is there a way to impose a restriction on what X can be? E.g. I might want myfunc1 to accept only double or int, or I might want myfunc2 to return only double* or int*.

Can I do that in the prototype?

many thanks in advance.
Last edited on Aug 6, 2010 at 10:32am
Aug 6, 2010 at 12:46pm
Maybe its possible if you only declare the specialized templates
1
2
template<> int* myfunc2<int>() { ... };
template<> int* myfunc2<char>() { ... };


Otherwise, function overloading
Aug 6, 2010 at 1:49pm
I think in your case function overloading is the better option. The whole point of templates is to allow any type.
Aug 6, 2010 at 3:15pm
+1 Dudester

If the bodies of the code will be similar for different types, but you only want specific types to be available, then I would have overloaded functions that call a hidden/private template member function. For example:

1
2
3
4
5
6
7
8
9
10
11
12
class MyClass
{
private:
  template <typename T> void myfunc1internal(T foo)
  {
    // do the actual work here
  }

public:
  void myfunc1(int foo)     { myfunc1internal(foo); }
  void myfunc1(double foo)  { myfunc1internal(foo); }
};
Aug 6, 2010 at 4:14pm
Thanks for the help!

I'm quickly learning that this language is not nearly as quick to code as PHP (which I'm used to), but its a lot faster!

So you pays your money and you takes your choice.
Aug 6, 2010 at 4:18pm
closed account (oz10RXSz)
In general it is not possible in C++, unless you wish to create an overloaded function for every type parameter you plan to support, just as Disch showed. It would be possible if concepts were accepted in C++0x, but we will have to wait for them for the next 5 years or more.
Last edited on Aug 6, 2010 at 4:19pm
Topic archived. No new replies allowed.