must inline a template member function ?

Hi dear all,
take a look at following code
// test.h
struct test
{
template<typename ...ARGS>
void demo(ARGS ...args);
};
// test.cpp
template<typename ...ARGS>
void test::demo(ARGS...args)
{

}
// demo.cpp
#include "test.h"
int main()
{
test t;
t.demo(1,2);
}

compile with
cl /nologo demo.cpp test.cpp
got the following error
error LNK2019: unresolved external symbol "public: void __cdecl test::demo<int,int>(int,int)" (??$demo@HH@test@@QEAAXHH@Z) referenced in function main

please help . many thanks !!!
Last edited on
The template function must be inline and visible, typically this is all done in the header file. You wouldn't normally place the code in a .cpp file to be compiled as a separate module.
thanks. I'll check the FAQ!
Last edited on
must inline a template

note that making a template "visible" (by putting it in a header file) is not the same as inlining a template, you are still able to use the inline keyword on templates!

Inline keyword has 2 different meanings:
ODR (One definition rule) and
Inline substitution

people usually don't understand this in case of templates by thinking that templates are implicitly inline like constexpr functions, but that's not true, anyway what is meant by that "templates are implicitly inline" if defined in a header?

it means they are implicitly ODR, but that does not make them inline as for inline substitution.

to make templates candidates for inline expansion, you must use the inline keyword explicitly, and the compiler is free to ignore that.

however if you omit the inline keyword templates are never used for inline expansion, but they are ODR, meaning only one definition in object code.

The highlight is that, ODR is always implicit, while inline expansion (that is putting the code in call site) is done by marking the template as inline

also note that inline keyword implies definition is put in a header file, while omitting the inline makes it possible to separate definition into a cpp file, but there are shortcomings for this approach and not useful for libraries.

Partial Reference:
https://isocpp.org/wiki/faq/templates#separate-template-class-defn-from-decl
As an example, consider the header file Foo.h which contains the following template class. Note that method Foo::f() is inline and methods Foo::g() and Foo::h() are not.

Last edited on
Topic archived. No new replies allowed.