gpt4 book ai didi

c++ - 获得与模板 arg 中传递的函数成员类型相同的类

转载 作者:搜寻专家 更新时间:2023-10-31 02:07:30 24 4
gpt4 key购买 nike

我正在尝试,但我不知道如何(但可能是不可能的)在将派生类的函数成员指针作为模板参数传递时捕获相同类型的类。

比如有这段代码,

class CObject{

public:
string m_id;

void setID(const char * id){
printf("assign id %s\n",id);
m_id=string(id);
}

~CObject(){}
};


class CDerivedObject:public CObject{
public:
~CDerivedObject(){};
};

有了这个函数模板,

template < typename _R, class _T, typename..._A>
void function_template_test(_R (_T:: *function_type)(_A...) )
{

printf("ObjectTypeIs: %s\n",typeid( _T).name());
}

在主函数中我调用function_template_test传递函数指针成员CDerivedObject::setID,

function_template_test(&CDerivedObject::setID);

如果我用 g++ 编译这段代码(我的最后一个版本是 5.4.0),它会打印出 7CObject,这意味着 _T 是 CObject 类型,但在参数中我传递了 CDerivedObject::setID。我知道函数setID函数属于CObject,所以编译器以这种方式获取类型,但是......

是否有可能捕获我传递给模板参数的类类型(即 _T 是 CDerivedObject)?

编辑 1

我的问题的解决方案可能是这样的,

template < class _C, class _R, typename _T, typename..._A>
void _function_template_test(_R (_T:: *function_type)(_A...) )
{

printf("ObjectTypeIs: %s\n",typeid( _C).name());
}

#define function_template_test(cl, fun)\
_function_template_test<cl>(&cl::fun)

然后我调用这个函数,

function_template_test(CDerivedObject,setID);

是一个解决方案,但我更喜欢模板而不是宏。

最佳答案

考虑这个程序:

struct Base { void foo() {} };
struct Derived: Base {};

auto main() -> int
{
int x = &Derived::foo;
}

这是使用 MinGW g++ 编译的结果:

[H:\forums\so\056]> g++ main.cppmain.cpp: In function 'int main()':main.cpp:6:23: error: cannot convert 'void (Base::*)()' to 'int' in initialization     int x = &Derived::foo;                       ^~~[H:\forums\so\056]> _

As you can see the type of &Derived::foo is void (Base::*)() (and yes, that's according to the standard).

I.e., when you ask

Is there a possible way to capture the class type I'm passing on template parameter

... that's what you're doing.

To make that type void (Derived::*)() you need a function declared in Derived.


For your case of calling a function that takes a member function pointer, you can alternatively specify all the template arguments explicitly. That works because a void (Base::*)() converts implicitly to void (Derived::*)(). And yes that's counter-intuitive, and constitutes a little loop-hole in the C++ type system, but it's the way the logic works out when you consider what kinds of objects a member function can be called on.


Re the loop-hole, here's an example (see ma, no casts!):

#include <iostream>
#include <stack>
using namespace std;

auto main()
-> int
{
stack<int> st;
for( int const i : {1, 2, 3} ) { st.push( i ); }

struct Hack: stack<int> { using stack<int>::c; };
int const n = (st.*&Hack::c).size();
cout << "That stack contains " << n << " items." << endl;
}

关于c++ - 获得与模板 arg 中传递的函数成员类型相同的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48601298/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com