【问题标题】:C++ undefined reference to template method [duplicate]C ++未定义对模板方法的引用[重复]
【发布时间】:2014-08-12 09:01:21
【问题描述】:

我试图在另一个类的方法中调用一个类的方法。以下代码可以正常工作,但是当我在单独的 .cpp 文件中定义 class SecondInvoke method 并且 not inline 就像现在一样,我收到以下错误: 未定义对“void Second::Invoke(First*, TMethodDelegate::OneParam::TMethodPtr_Const)”的引用。谁能向我解释一下为什么 Invoke 方法仅在定义 inline 时才有效?

// 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
}

【问题讨论】:

  • 对不起,我不想复制。我知道模板类必须在头文件中实现,但我不知道对于单个模板函数也是如此。

标签: c++ templates pointers methods inline


【解决方案1】:

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

见:Why can templates only be implemented in the header file?

【讨论】:

  • ...除非它们在所述实现文件中明确实例化...
  • 我明白了,非常感谢。
  • 所以不必内联,只需要在头文件中定义即可。再次非常感谢您。
猜你喜欢
  • 2013-02-01
  • 2010-11-09
  • 2014-04-30
  • 2012-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多