Understanding C++ member function template specialization

前端 未结 2 848
后悔当初
后悔当初 2021-02-05 15:07

I have the following class:

#pragma once
#include 
#include 

class testclass
{
public:
    template  T item(const s         


        
2条回答
  •  无人及你
    2021-02-05 16:01

    Sadly, this is not the whole story. The explicit specialization of the member template function 'item' must be unique throughout the program. If you were to create another translation unit that implemented another function that did the same thing as 'main' and linked that into your program, you would get multiple definitions. You have a couple of alternatives: (1) declare the specialization to be an inline function in the header (not a general solution); (2) declare the specialization in the header and define it in the '.cpp' file (general answer). This is a great example of the importance of understanding at a fundamental level how compilers and linkers implement the "physical linking" of various C++ constructs.

提交回复
热议问题