3

I tried a template specialization like bellow.

#include<iostream>
using namespace std;

template<class T1, class T2>
T1 something(T2 a);

template<class T2>
double something(T2 a){
    double b;
    return b;
}

int main(){
    something<double, double>(0.0);
}

However, this gives me a compilatoin error:

In function `main':
test.cpp:(.text+0x9): undefined reference to `double something<double, double>(double)'

Could you tell me how to fix it?

orematasaburo
  • 1,207
  • 10
  • 20
  • I can compile this exact code without error - are you sure this is **exactly** the code you are compiling? How are you compiling it? – BoBTFish Sep 07 '18 at 06:03
  • @BoBTFish I am really sorry, I pasted different one. Now, I edited. – orematasaburo Sep 07 '18 at 06:06
  • Please provide a [mcve]. – Passer By Sep 07 '18 at 06:12
  • 4
    This is **not** specialization, it is actually **overloading**: https://stackoverflow.com/a/8061522/1171191 – BoBTFish Sep 07 '18 at 06:21
  • You are getting that error because you are calling a function (overload) that is declared but not defined. – Daniel Langr Sep 07 '18 at 06:45
  • Possible duplicate of [What is an undefined reference/unresolved external symbol error and how do I fix it?](https://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix) – Daniel Langr Sep 07 '18 at 06:48

1 Answers1

5

This is not template specialization, but function template overloading.

The 1st overloading has two template parameters, the 2nd one has only one; when you call it with two specified template arguments like something<double, double>(0.0);, the 1st one will be selected in overload resolution; but it's not defined then leads to link error.


BTW: Function templates can only be full specialized, they can't be partial specialized. And in most cases function template overloading would do the work well.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405