C++ templates, undefined reference

前端 未结 4 1001
無奈伤痛
無奈伤痛 2020-11-27 07:08

I have a function declared like so:

template  
T read();

and defined like so:

template          


        
4条回答
  •  天命终不由人
    2020-11-27 07:38

    The problem is that a function template is not a function. It's a template for creating functions as needed.

    So for a template to work, the compiler intuitively needs two pieces of information: The template itself, and the type that should be substituted into it. This is unlike a function call, which the compiler can generate as soon as it knows that the function exists. It doesn't need to know what the function does, just that it looks like void Frobnicate(int, float), or whatever its signature is.

    When you declare the function template without defining it, you're only telling the compiler that such a template exists, but not what it looks like. That's not enough for the compiler to be able to instantiate it, it has to be able to see the full definition as well. The usual solution is to put the entire template in a header that can be included where needed.

提交回复
热议问题