gpt4 book ai didi

c++ - VS2010 : templates and overloaded functions 的解决方法

转载 作者:太空狗 更新时间:2023-10-29 21:47:45 24 4
gpt4 key购买 nike

我的代码与 mingw/g++ 编译器完美构建,但 MSVC (2010) 遇到错误。问题是重载的函数和模板。可能有人知道 MSVC 的解决方法?如果解决方法不存在(证明链接无效),它也会回答。

代码示例:

#include <iostream>

struct Function
{
virtual ~Function() {}
virtual void operator()() = 0;
};

template <typename Class, typename ARG1>
struct MemberFunction1 : public Function
{
typedef void (Class::*MEM_FUNC)(ARG1);
explicit MemberFunction1(Class * obj, MEM_FUNC func, ARG1 arg1) : m_object(obj), m_func(func), m_arg1(arg1) {}

virtual void operator()()
{
(m_object->*m_func)(m_arg1);
}

Class * m_object;
MEM_FUNC m_func;
ARG1 m_arg1;
};

struct FunctionStorage
{
explicit FunctionStorage(Function * func) : m_func(func) {}

virtual ~FunctionStorage()
{
if (m_func)
{
delete m_func;
m_func = 0;
}
}

void call() { (*m_func)(); }
Function * m_func;
};

struct MemberFunction : public FunctionStorage
{
template <typename Class, typename ARG1>
MemberFunction(Class * obj, void (Class::*func)(ARG1), ARG1 arg1) : FunctionStorage(new MemberFunction1<Class, ARG1>(obj, func, arg1)) {}
};


class Foo
{
public:
void funcWithParam(int value)
{
std::cout << "foo::funcWithParam(" << value << ")\n";
}
void funcWithParam(const char * msg)
{
std::cout << "foo::funcWithParam(" << msg << ")\n";
}
};

int main()
{
Foo f;
MemberFunction(&f, &Foo::funcWithParam, 5).call(); // problem here, if remove one of funcWithParam (stay only 1 function, no overload) all will be ok
MemberFunction(&f, &Foo::funcWithParam, "hello").call();
return 0;
}

我的输出:

main.cpp(65): error C2660: 'MemberFunction::MemberFunction' : function does not take 3 arguments
main.cpp(65): error C2228: left of '.call' must have class/struct/union
main.cpp(66): error C2660: 'MemberFunction::MemberFunction' : function does not take 3 arguments
main.cpp(66): error C2228: left of '.call' must have class/struct/union

Here is ideone构建结果。

最佳答案

Foo::funcWithParam 的两个重载匹配 MemberFunction(Class * obj, void (Class: :*func)(ARG1), ARG1 arg1),所以第二个参数类型不明确:编译器无法决定ARG1是int还是const char *.

有趣的是,如果你在模板构造函数中颠倒参数的顺序,即像这样:MemberFunction(Class * obj, ARG1 arg1, void (Class::*func)(ARG1) ) 并将您的调用站点更改为此:MemberFunction(&f, 5, &Foo::funcWithParam)它会起作用。编译器首先遇到第二个参数,从中推断类型 ARG1 是 int。然后它继续处理第三个参数,因为它现在知道 ARG1 是 int,所以它知道要选择 &Foo::funcWithParam 的哪个重载。

我不确定在这种情况下标准规定的行为应该是什么,但其中一个编译器肯定有错误,很可能是 VS2010。

关于c++ - VS2010 : templates and overloaded functions 的解决方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12526760/

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