Why don't templates declared in the header structure violate ODR and specialization?

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 inline to prevent ODR violation, inline will merge the translation table, avoiding conflict.

But why don't I need inline on isImplemented inside structure A? Maybe this question can be extended, why, if a method is declared inside a struct / class in the header, it doesn't need inline? How can I figure it out it would create symbols in every object file (.o) it is called, violating the ODR, why isn't this happening?

+3


source to share


2 answers


You don't need this for two reasons:



  • Every function defined in a class definition is implicit inline

    .
  • The template does not require a keyword inline

    . Remember, your original function is a template, but your specialization is not.
+3


source


This indicates what is template<typename T> bool isImplemented()

NOT a function. It is a template for a function and will only exist (as code) once you've done it with template<> inline bool A::isImplemented<int>()

.

inline

not necessary here. The program compiles and runs without it.

The weird thing is that yours struct A

doesn't depend on any template parameter nor on a method isImplemented()

, so I'm still trying to figure out your intent.

A simple use of your functions might look like this:

int  main( )
{
    A a;

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

      

And the output is:



int Implemented
Not Implemented

      

And basically you can tell which specializations you explicitly implemented from the generic ones. This is what you need?

EDIT:

Given the comment on my answer, I believe the original question here answered well:

+1


source







All Articles