简体   繁体   English

为什么在标题的结构中声明的模板不违反ODR和专业化呢?

[英]Why templates declared in the struct on the header dont violate ODR and specialization does?

I have this code: 我有这个代码:

#include <iostream>

struct A
{
    template<typename T> bool isImplemented()
    {
                std::cout << "Not Implemented" << std::endl;
                return false;
    }
};

template<> inline bool A::isImplemented<int>()
{
    std::cout << "int Implemented" << std::endl;
    return true;
}

I can understand why the template specialization needs the inline, in order to prevent the ODR to be violated the inline will merge the translation table avoiding a conflict. 我可以理解为什么模板专门化需要内联,为了防止ODR被违反,内联将合并转换表避免冲突。

But, why I don`t need an inline on the isImplemented inside the struct A? 但是,为什么我不需要在结构A中的isImplemented上内联? Maybe that question can be extended to, why if the method is declared inside the struct/class on the header it does not need the inline? 也许这个问题可以扩展到,为什么如果方法在头部的struct / class中声明它不需要内联? As I can understand, it would create the symbols on every object file (.o) that it is called, violating the ODR, why that does not happen? 据我所知,它会在每个被调用的目标文件(.o)上创建符号,违反ODR,为什么不会发生?

You do not need it for two reasons: 您不需要它有两个原因:

  • Every function defined within the definition of the class is implicit inline . 在类的定义中定义的每个函数都是隐式inline
  • A template doesn't need inline keyword. 模板不需要inline关键字。 Remember, your original function is a template, while specialization is not. 请记住,您的原始功能是模板,而专业化则不是。

The point to highlight here is that template<typename T> bool isImplemented() IS NOT a function . 这里要强调的是template<typename T> bool isImplemented() 不是函数 It is a template to a function and will only exist (as code) once specialized, like you did with template<> inline bool A::isImplemented<int>() . 它是一个函数的模板,一旦专门化就会存在(作为代码),就像你使用template<> inline bool A::isImplemented<int>()

The inline here is not mandatory. 这里的inline不是强制性的。 Program compiles and runs perfectly without it. 程序编译并在没有它的情况下完美运行。

Strangely your struct A does not depend on any template parameter neither isImplemented() method so I am still trying to figure out your intention. 奇怪的是你的struct A不依赖于任何模板参数既不是isImplemented()方法,所以我仍然试图找出你的意图。

A simple usage of your functions might look like this: 函数的简单用法可能如下所示:

int  main( )
{
    A a;

    a.isImplemented< int >( );
    a.isImplemented< double >( );
}

And the output: 并输出:

int Implemented
Not Implemented

And basically you are able to tell wich specializations you have explicitly implemented from the generic ones. 基本上你可以告诉你从通用的那些明确实现的专业化。 Is it what you need? 这是你需要的吗?

EDIT: 编辑:

Given the comment on my answer, I believe the original question is nicely answered here: 鉴于对我的回答的评论,我相信原来的问题在这里很好地回答:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM