multiple definition of template specialization

Hi, I'm reading that when you fully specialize function templates or members of class template you only have to put declaration of that specialization in the header file where the original template definition are and implement it in .cpp file so there wouldn't be multiple definition error.

As I read here
http://stackoverflow.com/questions/4445654/multiple-definition-of-template-specialization-when-using-different-objects
2015 answer is still addressing this problem.

I tried to recreate this problem but it worked fine for me. Here is what I tried

templates.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#pragma once
#include <iostream>

//function
template<typename T>
void func(T arg){
	std::cout << "inside generic function\n";
}

template<>
void func<int>(int){
	std::cout << "inside \"int\" specialization function\n";
}

//class
template<typename T>
class X {
public:
	void print() const;
};

template<typename T>
void X<T>::print() const{
	std::cout << "inside generic X template\n";
}

template<>
void X<int>::print() const{
	std::cout << "inside specialization X<int> template\n";
}


function.h
1
2
3
4
5
6
7
8
9
#pragma once
#include "templates.h"

void random_func()
{
	func(5.5);
	X<double> x;
	x.print();
}


main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
#include "templates.h"
#include "function.h"

int main()
{
	//calling specializations
	func<int>(3);
	X<int> x;
	x.print();
	
	//calling original definitions
	random_func();
}


Why am I not getting linker error about violation or ODR? Are there any new rules to this?
The problem only occur when you have more than one source file that includes the file.
Ohh yea, splitting function.h into h and cpp files made it to "work"! :) Tnx a lot man!
Last edited on
Topic archived. No new replies allowed.