C ++未定义的模板方法引用

时间:2014-08-12 09:01:22

标签: c++ templates pointers methods inline

我试图在另一个类的方法中调用一个类的方法。以下代码正常运行,但是当我在单独的 .cpp 文件中定义类第二调用方法不是内联< / strong>就像现在一样,我收到以下错误: 未定义引用&#39; void Second :: Invoke(First *,TMethodDelegate :: OneParam :: TMethodPtr_Const)&#39; 。任何人都可以向我解释为什么调用方法仅在定义内联时才有效?

// MethodDelegate.h
#pragma once

template <class TClass>
class TMethodDelegate
{
public:
    /** TMethodDelegate with no parameters */
    template <typename TRetValue>
    class NoParams
    {
    public:
        typedef TRetValue(TClass::*TMethodPtr)();
        typedef TRetValue(TClass::*TMethodPtr_Const)() const;

    private:
        inline NoParams() {}
    };

    /** TMethodDelegate with one parameter */
    template <typename TRetValue, typename TParam0>
    class OneParam
    {
    public:
        typedef TRetValue(TClass::*TMethodPtr)(TParam0);
        typedef TRetValue(TClass::*TMethodPtr_Const)(TParam0) const;

    private:
        inline OneParam() {};
    };

private:
    inline TMethodDelegate() {}
};

// First.h
#pragma once

#include <iostream>

using std::cout;
using std::endl;

class First
{
public:
    inline void PrintInt(int number) const
    {
        cout << number << endl;
    }
};

// Second.h
#pragma once

#include "MethodDelegate.h"

class Second
{
public:
    // When defined in a separate .cpp file I get an undefined error when I am trying to call the method in the main function
    template <class TClass>
    inline void Invoke(TClass* object, typename TMethodDelegate<TClass>::template OneParam<void, int>::TMethodPtr_Const Func)
    {
        if (object != 0 && Func != 0)
        {
            int number = 10;
            (object->*Func)(number);
        }
    }
};

// main.cpp
#include "First.h"
#include "Second.h"

int main()
{
    First first;
    Second second;

    second.Invoke(&first, &First::PrintInt); // I get the error at this line. If I comment the line - the code is compiling. This is only if the Invoke method is defined in a separate .cpp file of course
}

1 个答案:

答案 0 :(得分:3)

模板类/函数必须在头文件中定义,而不是在.cpp

中定义

请参阅:Why can templates only be implemented in the header file?