【发布时间】:2014-08-12 09:01:21
【问题描述】:
我试图在另一个类的方法中调用一个类的方法。以下代码可以正常工作,但是当我在单独的 .cpp 文件中定义 class Second 的 Invoke 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