(默认)为每个可变类型构造一个对象 [英] (Default) construct an object for every variadic type
问题描述
请考虑以下代码段:
void Foo(std::string str1, std::string str2) {}
template<typename... Types>
void Bar()
{
Foo(Types{}...); // wont compile
}
Bar<std::string, std::string>();
我想在这里做的是默认构造两个 std :: string
对象,并将它们传递给 Bar
方法中的 Foo
。然而我的虚假尝试(其中一个在代码段)不编译,所以我想知道是否这是可能的。
What I want to do here is to default construct two std::string
objects inside the Bar
method and pass them to Foo
. However my vain attempts (one of them being in the snippet) wont compile so I am wondering whether this is even possible.
我编译VC 2013,抛出编译器错误对我。如注释中所述,其他编译器可以处理它。
I compiled with VC 2013, which throws compiler errors at me. As stated in the comments, other compilers can handle it. Can anyone tell whether the above snippet is standard conform?
推荐答案
这是MSVC可变参数模板扩展过程中的一个问题,当它解包类型列表时,它无法将其识别为适合构造函数调用。作为解决方法,您可以执行类型转换以强制编译器识别它们:
It's a problem in the MSVC variadic template expansion process; when it unpacks the list of types it fails to recognise them as suitable for a constructor call. As a workaround, you can perform a type transformation to force the compiler to recognise them:
template<typename T> using identity_t = T; // NEW CODE
void Foo(int, int);
template<typename... Types>
void Bar()
{
Foo(identity_t<Types>{}...); // use identity type transformation
}
int main() {
Bar<int, int>();
}
我尚未设法找到问题编号。
I haven't managed to find an issue number yet.
这篇关于(默认)为每个可变类型构造一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!