(Default) construct an object for every variadic t

2020-03-02 03:55发布

Consider this code snippet:

void Foo(std::string str1, std::string str2) {}

template<typename... Types>
void Bar()
{
    Foo(Types{}...); // wont compile
}

Bar<std::string, std::string>();

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.

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?

2条回答
▲ chillily
2楼-- · 2020-03-02 03:59

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.

查看更多
老娘就宠你
3楼-- · 2020-03-02 04:20

This crashes the VC 2013 compiler for me. The errors seem to indicate that it has some problems parsing the code. So when the compiler crashes it must be a compiler bug.

1>main.cpp(23): error C2144: syntax error     : 'std::string' should be preceded by ')'
1>          main.cpp(28) : see reference     to function template instantiation 'void Bar<std::string,std::string>(void)' being compiled
1>main.cpp(23): error C2660: 'Foo' :     function does not take 0 arguments
1>main.cpp(23): error C2143: syntax error     : missing ';' before '{'
1>main.cpp(23): error C2143: syntax error     : missing ';' before ','
1>c1xx : fatal error C1063: INTERNAL COMPILER ERROR
1>           Please choose the Technical Support command on the Visual C++ 
1>           Help menu, or open the Technical Support help file for more information
1>cl : Command line warning D9028: minimal rebuild failure, reverting to normal build
1>
1>Build FAILED.
查看更多
登录 后发表回答