static function template?

HI, how to make a static function template?

I have this code

F.h --- header file

1
2
 template<unsigned N, unsigned M>
static int compare(const char(&p1)[N], const char(&p2)[M]);


F.cpp

1
2
3
 int Function_templates::compare(const char(&p1)[N], const char(&p2)[M]){ 
	return strcmp(p1, p2);
}


But when i call this to another class using namespace
1
2
3
4
5
6
namespace Template_Programming{
	int main(){
		cout << Function_templates::compare("hi", "yow");
		return 0;
	}
}


i always got this error

Error 1 error LNK2019: unresolved external symbol "public: static int __cdecl Function_templates::compare<3,4>(char const (&)[3],char const (&)[4])" (??$compare@$02$03@Function_templates@@SAHAAY02$$CBDAAY03$$CBD@Z) referenced in function "int __cdecl Template_Programming::main(void)" (?main@Template_Programming@@YAHXZ)


Templates are entirely defined in the headers.

(also, if Function_templates is a namespace, using "static" is usually a bad idea)

Also, the main function shouldn't be in a user-defined namespace: the runtime isn't going to call Template_Programming::main to start your program, it's going to call main.
Last edited on
The function main() cannot be within a namespace it must be within the global scope.

Also when dealing with templates both the definition and the implementation must be within the same compilation unit, usually meaning they are in the same file, most often a header file.

BUt if its going to call the main why does this work


static void showme();

1
2
3
void Function_templates::showme(){
	cout << compare("hi","yow");
}


1
2
3
4
5
namespace Template_Programming{
	int main(){
		cout << Function_templates::compare("hi", "yow");
		return 0;
	}


This code works..
Your compiler is allowing non-standard main definitions. It will not work for the majority of people.
Standard wrote:
3.6 Start and termination [basic.start]
3.6.1 Main function [basic.start.main]
1 A program shall contain a global function called main, which is the designated start of the program.
As you can see C++ Standard clearly requires that main() should not be a part of any namespace.
Topic archived. No new replies allowed.