【发布时间】:2016-05-09 17:14:32
【问题描述】:
在我第一次尝试可变参数模板时,我试图创建一个函数,该函数使用模板参数的所有组合实例化派生类。这个想法是让运行时选项类能够选择要使用的确切模板实例化。我已经能够让基本案例使用 1 和 2 个模板参数。但是一般情况下不起作用,下面第三次调用 SelectInstance 编译失败,出现以下错误:
候选函数不可行:需要 3 个参数,但提供了 2 个 AbstractBase *SelectInstance(Func func, Args... args)
完整代码如下:
#include <memory>
#include <iostream>
struct Options
{
bool GetFirstParameter() { return true; }
bool GetSecondParameter() { return false; }
bool GetThirdParameter() { return true; }
};
struct AbstractBase
{
virtual void PrintMe() = 0;
};
template<class... Args>
struct Derived : public AbstractBase
{
virtual void PrintMe() { std::cout << __PRETTY_FUNCTION__ << std::endl; }
};
template<class... Args>
AbstractBase *SelectInstance()
{
return new Derived<Args...>();
}
template<class Func, class... UnpackedArgs>
AbstractBase *SelectInstance(Func func)
{
if (func())
return SelectInstance<float, UnpackedArgs...>();
else
return SelectInstance<double, UnpackedArgs...>();
}
template<class Func, class... Args, class... UnpackedArgs>
AbstractBase *SelectInstance(Func func, Args... args)
{
if (func())
return SelectInstance<Args..., float, UnpackedArgs...>(args...);
else
return SelectInstance<Args..., double, UnpackedArgs...>(args...);
}
int main()
{
Options opts;
std::unique_ptr<AbstractBase> one(
SelectInstance(
std::bind(&Options::GetFirstParameter, &opts)
)
);
one->PrintMe();
std::unique_ptr<AbstractBase> two(
SelectInstance(
std::bind(&Options::GetFirstParameter, &opts),
std::bind(&Options::GetSecondParameter, &opts)
)
);
two->PrintMe();
// this one fails to compile!
std::unique_ptr<AbstractBase> three(
SelectInstance(
std::bind(&Options::GetFirstParameter, &opts),
std::bind(&Options::GetSecondParameter, &opts),
std::bind(&Options::GetThirdParameter, &opts)
)
);
three->PrintMe();
}
我可能不正确地使用可变参数模板将仿函数转换为新的参数包。任何指导表示赞赏。
【问题讨论】:
标签: c++ templates variadic-templates