本文介绍了通过const限定符(成员函数指针的)重载分辨率?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我仅在参数的const限定符上重载类的成员函数时(这是不同类的成员函数指针),编译器将解决重载并按预期执行.
当我为非成员函数尝试相同的重载时,编译器(VS2010 Express)抱怨链接器错误.

有谁知道为什么吗?

When I overload a class''s member function solely on the const qualifier of the parameter (which is a different class''s member function pointer), the compiler resolves the overload and performs as expected.
When I attempt the same overload for a non-member function, the compiler (VS2010 Express) complains of linker errors.

Does anyone know why ?

//Header.h

#pragma once

#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
#include <iostream>

struct Component
{
	int Execute(bool X) { return 0; }

	int ConstExecute(bool X) const { return 0; }
};

struct Tester
{
	void Con( int (Component::*MFP)(bool) )
	{ std::cout << "Tester::Con Passed Non-Const MFP\n"; };

	void Con( int (Component::*MFP)(bool) const )
	{ std::cout << "Tester::Con Passed Const MFP\n"; };
};


void Con( int (Component::*MFP)(bool) )
{ std::cout << "Con Passed Non-Const MFP\n"; };

void Con( int (Component::*MFP)(bool) const )
{ std::cout << "Con Passed Const MFP\n"; };


//Main.cpp

#include "Header.h"

int _tmain(int argc, _TCHAR* argv[])
{
	// In Main
	Tester MyTester;
	MyTester.Con( &Component::Execute );
	MyTester.Con( &Component::ConstExecute );

	Con( &Component::Execute );
        // LNK2005: Con(int (__thiscall Component::*)(bool) already defined
	Con( &Component::ConstExecute );
        // LNK2005: Con(int (__thiscall Component::*)(bool)const ) already defined

	char X;
	std::cin >> X;
	return 0;
}



注释掉对非成员Con函数的调用会产生:
"Tester :: Con通过了非常量MFP"
"Tester :: Con通过了Const MFP"
符合预期.



Commenting out the calls to the non-member Con Function produces:
"Tester::Con Passed Non-Const MFP"
"Tester::Con Passed Const MFP"
as expected.

推荐答案

inline void Con( int (Component::*MFP)(bool) )
{ std::cout << "Con Passed Non-Const MFP\n"; };

inline void Con( int (Component::*MFP)(bool) const )
{ std::cout << "Con Passed Const MFP\n"; };



inline关键字使编译器本质上可以在调用函数的任何地方复制并粘贴函数代码,而无需定义实际函数.这有点麻烦,但是可以.



The inline keyword makes the compiler essentially copy and paste the function code everywhere the function is called, without defining an actual function. This is a bit of a hack up, but works.



这篇关于通过const限定符(成员函数指针的)重载分辨率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 22:52