【发布时间】:2017-05-29 17:03:08
【问题描述】:
我了解了一些关于可变参数模板的知识,并在 Internet 上搜索了一些示例,现在尝试编写一些棘手的代码来调用成员一个可变参数类模板的方法及其一个字段。我不明白为什么它不起作用。请帮忙。
这里是示例类:
class BarBase
{
public:
BarBase() = default;
virtual void call() = 0;
};
template<typename O, typename M, typename... A>
class Bar
: public BarBase
{
public:
Bar(O* o, M m, A&&... a)
: BarBase()
, m_o(o), m_m(m), m_a(std::forward<A>(a)...)
{ }
void call() override final
{
callInnerWithArgsInside();
}
private:
void callInnerWithArgsInside()
{
(m_o->*m_m)(m_a); // Some errors happends here
}
O* m_o;
M m_m;
std::tuple<typename std::remove_reference<A>::type...> m_a;
};
template<typename O, typename M, typename... A>
BarBase* crateBar(O* o, M m, A&&... a)
{
return new Bar<O, M, A...>(o, m, std::forward<A>(a)...);
}
然后从 main 调用:
struct Foo
{
void foo(int ii, float ff, std::string ss)
{
std::cout << "called" << std::endl;
}
};
int main()
{
Foo f;
int i = 10;
float ff = 20.2f;
std::string s = "Hello";
BarBase* bar = crateBar(&f, &Foo::foo, i, ff, s);
bar->call();
}
错误:
main.cpp
1>d:\drafts_tests\main.cpp(203): error C2198: 'void (__thiscall Foo::* )(int,float,std::string)' : 调用的参数太少
1> d:\drafts_tests\main.cpp(202) : 在编译类模板成员函数'void Bar::callInnerWithArgsInside(void)'时
1> 与
1> [
1> O=Foo
1> , M=void (__thiscall Foo::* )(int,float,std::string)
1>]
1> d:\drafts_tests\main.cpp(197) : 请参阅正在编译的函数模板实例化 'void Bar::callInnerWithArgsInside(void)' 的参考
1> 与
1> [
1> O=Foo
1> , M=void (__thiscall Foo::* )(int,float,std::string)
1>]
1> d:\drafts_tests\main.cpp(214) : 请参阅正在编译的类模板实例化“Bar”的参考
1> 与
1> [
1> O=Foo
1> , M=void (__thiscall Foo::* )(int,float,std::string)
1>]
1> d:\drafts_tests\main.cpp(225) : 请参阅正在编译的函数模板实例化 'BarBase *crateBar(O *,M,int &,float &,std::string &)' 的参考
1> 与
1> [
1> O=Foo
1> , M=void (__thiscall Foo::* )(int,float,std::string)
1>]
========== 构建:0 成功,1 失败,0 最新,0 跳过 ==========
【问题讨论】:
-
它到底是怎么不工作的?
-
我想你会找到this question 一个迷人的读物。
标签: c++ c++11 variadic-templates