Is the inline keyword relevant if the function is defined in the header file?

All code From what I read, A1 and A2 are identical, but I do not if A3 is identical to A2. I know that the code will compile since all classes A are tmemplated.

Note. All class and method declarations are in the .h file.

template <typename _Ty>
class A1 {
public:
    A1();
    void foo() { ... }
};


template <typename _Ty>
class A2 {
public:
    A2();
    void foo();
};

template <typename _Ty>
inline void A2<_Ty>::foo() { ... }


template <typename _Ty>
class A3 {
public:
    A3();
    void foo();
};

template <typename _Ty>
void A3<_Ty>::foo() { ... } // note: No inline keyword here.

PS I saw variations of this question on stackoverflow, but not this exact question.

+3
source share
2 answers

Yes, it makes sense, but does not have much effect in combination with templates.

inline , , , "select-one" ( 't ). .

inline , , , , .

+8

inline , ?

. msvc, g++. BECAUSE inline:


main.cpp

#include "a.h"

int main(int argc, char** argv){
    A obj;
    obj.f();
    a();
    b();
    return 0;
}

#ifndef A_HEADER
#define A_HEADER

class A{
public:
    void f();
};

void a(){
}

void b();

void A::f(){
}

#endif

b.cpp

#include "a.h"

void b(){
    A obj;
    obj.f();
    a();
}

*. pro file ( Qt 4):

TEMPLATE = app
TARGET = 
DEPENDPATH += .
INCLUDEPATH += .

HEADERS += a.h
SOURCES += b.cpp main.cpp

:

cl.exe:


main.obj : error LNK2005: "void __cdecl a(void)" (?a@@YAXXZ) already defined in b.obj
main.obj : error LNK2005: "public: void __thiscall A::f(void)" (?f@A@@QAEXXZ) already defined in b.obj
debug\1234.exe : fatal error LNK1169: one or more multiply defined symbols found

++:


debug/main.o: In function `Z1av':
D:\c++\1234/a.h:6: multiple definition of `a()'
debug/b.o:D:\c++\1234/a.h:6: first defined here
debug/main.o:D:\c++\1234/a.h:11: multiple definition of `A::f()'
debug/b.o:D:\c++\1234/a.h:11: first defined here
collect2: ld returned 1 exit status
make[1]: *** [debug/1234.exe] Error 1
make: *** [debug] Error 2

, , ? *.cpp . "", , .obj/.o A::f() a(). Linker , . , .

- .

0

All Articles