【发布时间】:2021-10-15 12:52:52
【问题描述】:
假设我下面有两个函数,在Foo()函数中,如何将hw字符串打包成args转发给Bar()?
我试过std::bind,但没用。
template<typename T, typename... Args>
void Bar(Args&&... args)
{
// do something with args
}
template<typename T, typename... Args>
void Foo(Args&&... args)
{
if (typeid(T) == typeid(std::string)) {
std::string hw = "Hello, world!";
Bar<T>(std::forward<Args>(hw, args)...); // how to add hw to the forward list?
}
else {
Bar<T>(std::forward<Args>(args)...);
}
}
编辑:我终于找到了我的错误!对于那些想知道为什么hw 没有被转发到Bar() 的人,即使你做得对,请注意else 分支中的Bar()。如果Bar() 需要不同类型的参数,具体取决于T,并且代码无法编译,则else 分支可能会发出编译器错误。正如@JeJo 提到的,我应该改用if constexpr。
您可能会发现这篇文章很有帮助: using std::is_same, why my function still can't work for 2 types
【问题讨论】:
标签: c++ templates c++17 perfect-forwarding function-templates