Dan
Dan

Reputation: 2886

Does a template function with different definitions cause undefined behaviour?

0.cc

template <class T>
T get(){
 return 5;
}

int get(){
 return 6;
}

int main(){
 return get<int>();
}

1.cc

template <class T>
T get(){
 return 7;
}
template int get<int>(); // This forces code generation.

Compiling with g++ -Wall 0.cc 1.cc causes no link errors, returned output is 5.

Questions

1- Do templates have external linkage by default even if extern isn't used?

https://en.cppreference.com/w/cpp/language/storage_duration

names of all templates not listed above (that is, not function templates declared static).

2- Does the linker treat multiple templates like inline functions? i.e it chooses 1 out of many definitions and having different definitions causes UB? https://stackoverflow.com/a/66356946

3- Why doesn't int get(){} cause a link error? do template functions and regular functions have different symbols?

Upvotes: 0

Views: 169

Answers (2)

eerorika
eerorika

Reputation: 238361

Does a template function with different definitions cause undefined behaviour?

Yes.

1- Do templates have external linkage by default even if extern isn't used?

Yes, template functions have external linkage unless declared in anonymous namespace or if declared static or if attached to a module and is not exported.

2- Does the linker treat multiple templates like inline functions?

Yes. Implicit instantiations of function templates are treated the same as inline functions in this regard.

and having different definitions causes UB

Yes. Technically, the program is ill-formed, but the distinction between those doesn't really matter at runtime.

3- Why doesn't int get(){} cause a link error?

Overloading function template with a function is well-formed.

Upvotes: 3

Does a template function with different definitions cause undefined behaviour?

Answerr: Well, Yes, templates do behave undefined if you define them in multiple ways. There should be only one definition

BUT
You can use template in some other scope in with different definition

Do templates have external linkage by default even if external isn't used? Answer:

Yes,
Templates will cause external linkage in normal circum stances but some exceptions are
Defining them in some outer namespace or using them as an exports.module

Does the linker treat multiple templates like inline functions? i.e it chooses 1 out of many definitions and having different definitions Answer: Obviously, Templates are treated as an inline function

Upvotes: -1

Related Questions