【发布时间】:2021-12-17 05:07:03
【问题描述】:
我在MSVC v19.28 编译器上遇到了一个有趣的问题(更高版本修复了这个问题),其中const char* 被传递给可变参数模板class 无法正确解决。如果将const char* 传递给可变参数模板函数,则没有错误。
为了清楚起见,这里是代码:
#include <type_traits>
template <typename... T_Args>
struct Foo
{
template <typename T_Func>
void foo(T_Func func, T_Args&&... args)
{
func(std::forward<T_Args>(args)...);
}
};
template <typename T_Func, typename... T_Args>
void bar(T_Func func, T_Args&&... args)
{
func(std::forward<T_Args>(args)...);
}
int main()
{
bar([](int, float, const char* c){ }, 5, 5.0f, "Hello world");
// <source>(26): error C2672: 'Foo<int,float,const char *>::foo': no matching overloaded function found
// <source>(26): error C2440: 'initializing': cannot convert from 'const char [12]' to 'const char *&&'
// <source>(26): note: You cannot bind an lvalue to an rvalue reference
Foo<int, float, const char*> f;
f.foo([](int, float, const char* c){ }, 5, 5.0f, "Hello world");
// this compiles, but what are the repurcussions of std::move() on a string literal?
Foo<int, float, const char*> g;
g.foo([](int, float, const char* c){ }, 5, 5.0f, std::move("Hello world"));
}
由于我在一个大型团队工作,我无法推荐升级工具链/编译器,因此我正在寻找解决方法,直到可以更新编译器。
其中一种解决方法是使用std::move("Hello world")。 std::move 在做什么?const char* 有什么潜在的副作用?
【问题讨论】:
-
另一种解决方法:
+"Hello world"Demo。 -
你真的想要右值引用吗(由类固定,没有转发引用)。
-
注:你不是在打电话给
bar<lambda, int, float, const char *>,你是在打电话给bar<lambda, int, float, const char(&)[12]> -
@Caleth 对 - 我不完全理解为什么
const char(&)[12]不能衰减到const char*- 但我理解为什么在成员函数调用中没有推断出参数包,这是对我的疏忽部分
标签: c++ variadic-templates perfect-forwarding