【问题标题】:(Default) construct an object for every variadic type(默认)为每个可变参数类型构造一个对象
【发布时间】:2014-02-06 19:54:17
【问题描述】:

考虑这段代码sn-p:

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

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

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

我在这里要做的是在Bar 方法中默认构造两个std::string 对象并将它们传递给Foo。但是我徒劳的尝试(其中一个在 sn-p 中)无法编译,所以我想知道这是否可能。

我使用 VC 2013 编译,这会引发编译器错误。如 cmets 中所述,其他编译器可以处理它。谁能说出上面的 sn-p 是否符合标准?

【问题讨论】:

  • @0x499602D2 有趣,用 VC 2013 尝试了你的代码,但它失败了(正如我之前观察到的那样),可能是编译器错误
  • 也适用于 clang 3.5,你的编译器和版本是什么?

标签: c++ visual-c++ c++11 variadic-templates compiler-bug


【解决方案1】:

是MSVC可变参数模板扩展过程中的问题;当它解包类型列表时,它无法将它们识别为适合构造函数调用。作为一种解决方法,您可以执行类型转换以强制编译器识别它们:

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>();
}

我还没有找到问题编号。

【讨论】:

  • template&lt;typename T&gt; using identity_t = T; 也可以工作,不需要typename::type 装饰。
【解决方案2】:

这会使我的 VC 2013 编译器崩溃。这些错误似乎表明它在解析代码时遇到了一些问题。所以当编译器崩溃时,它一定是编译器的错误。

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.

【讨论】:

  • @Manu343726 不太可能,因为他们还没有完成 C++98 功能的实现,而且他们已经有 16 年的时间来研究该标准版本。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-09-27
  • 2019-11-22
  • 2013-02-06
  • 1970-01-01
  • 2017-04-01
  • 1970-01-01
  • 2011-07-18
相关资源
最近更新 更多