(Default) construct an object for every variadic type

笑着哭i 提交于 2019-11-30 04:37:34

问题


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?


回答1:


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.




回答2:


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.


来源:https://stackoverflow.com/questions/21612672/default-construct-an-object-for-every-variadic-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!