1

I tried this but this shows an error

template<>
int add(int a, int b)
{
    return a + b;
}

But when I write the below code it works fine

template<typename T>
T add(T a, T b)
{
    return a + b;
}
template<>
int add(int a, int b)
{
    return a + b;
}
Marek R
  • 32,568
  • 6
  • 55
  • 140
Shekhar
  • 11
  • 1
  • 4
    Specialization only makes sense when you have something to specialize - i.e. the primary template. – wohlstad Oct 14 '22 at 11:45
  • 6
    Why would you want that anyway - if you just want an `add` function that takes 2 `int`s why not use a regular function ? – wohlstad Oct 14 '22 at 11:46
  • I'm not entirely sure about your example. Did you try `template<> int add(int a,int b){ return a+b; }` without having `templateT add(T a,T b){return a+b;}`? In that case I'd like to ask why you need this and what you've expected to happen? What should happen when you specialize a template that doesn't exist? – Lukas-T Oct 14 '22 at 11:51
  • You can't specialize anything which is not at least declared in general case. Anyway why you need a template at all in this case? Classic old fashioned overload does the job. – Marek R Oct 14 '22 at 12:06
  • 1
    Dupe: [C++ template specialization without default function](https://stackoverflow.com/questions/1629406/c-template-specialization-without-default-function) – Jason Oct 14 '22 at 12:12

2 Answers2

3

You need a primary template declaration, otherwise the compiler wouldn't know what part of the function would be templated. But you don't need to provide a primary definition. So you can do:

template<typename T>
T add(T a, T b);

template<>
int add(int a, int b) {
    return a + b;
}
G. Sliepen
  • 7,637
  • 1
  • 15
  • 31
  • 3
    It is also possible to declare template function as deleted `template T add(T a, T b) = delete;` to get compilation error on instantiation instead of linker error. – dewaffled Oct 14 '22 at 12:36
0

Can I use specialized template without the primary template in c++

No, specialization by definition can't exist without the primary template. We need a primary template so that we can specialize(either explicitly or partially) it for some(or all) template parameters.

Jason
  • 36,170
  • 5
  • 26
  • 60