【问题标题】:Why passing T from outer template as default argument to std::function causes compilation error?为什么将外部模板中的 T 作为默认参数传递给 std::function 会导致编译错误?
【发布时间】:2013-04-07 02:16:56
【问题描述】:

我创建了一个模板类,并将 T 作为默认类型参数传递。但是,这会导致编译失败。任何人都可以解释会发生什么?谢谢!

PS。我使用的编译器是VS2012。

#include <functional>

using namespace std;

template <typename T = void()>
struct delegate
{
    typedef function<T> function_t;

    function_t f;
};

int main()
{
    delegate<> d;

    return 0;
}

编译器输出:

1>.\Microsoft Visual Studio 11.0\VC\include\functional(554): error C2027: use of undefined type 'std::_Get_function_impl<_Tx>'
1>          with
1>          [
1>              _Tx=void (__cdecl *)(void)
1>          ]
1>          test.cpp(12) : see reference to class template instantiation 'std::function<_Fty>' being compiled
1>          with
1>          [
1>              _Fty=void (__cdecl *)(void)
1>          ]
1>          test.cpp(17) : see reference to class template instantiation 'delegate<>' being compiled
1>.\Microsoft Visual Studio 11.0\VC\include\functional(555): error C2504: 'type' : base class undefined
1>.\Microsoft Visual Studio 11.0\VC\include\functional(558): error C2027: use of undefined type 'std::_Get_function_impl<_Tx>'
1>          with
1>          [
1>              _Tx=void (__cdecl *)(void)
1>          ]
1>.\Microsoft Visual Studio 11.0\VC\include\functional(558): error C2146: syntax error : missing ';' before identifier '_Mybase'
1>.\Microsoft Visual Studio 11.0\VC\include\functional(558): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int

【问题讨论】:

  • 看起来像一个 MSVC 编译器错误。在 g++ 4.7.0 下编译良好。
  • @Yuushi 真的吗?非常感谢。我只是想制作一个相当于 function. 的默认版本的 function
  • 编译器将您的T 转换为void(*)() 而不是void(),然后将其传递给std::function,这不是传递给std::function 的有效类型。如果你真的想解决这个问题,你可以编写一个解决方法,将A(B...)A(*)(B...) 作为一个参数,将template&lt;typename&gt;class F 作为另一个参数,并使用F&lt;A(B...)&gt;
  • 这绝对是一个编译器错误。我已在我们的内部数据库中将其归档为 DevDiv#671343。
  • @Patz 恭喜 - MS 本身的录取!

标签: c++ templates visual-c++ visual-studio-2012 c++11


【解决方案1】:

正如您的问题中的 cmets 所示:这只是 Visual Studio 中的一个错误,您的 C++ 代码没有任何问题。 @Stephan-T-Lavavej 说他已将其归档为 DevDiv#671343。

假设@Yakk 的诊断是正确的(MSVC 错误地将T 视为void(*)() 而不是void()),我之前提出了“可能的解决方法”

typedef function<typename remove_pointer<T>::type> function_t;

但正如@JoshPeterson 在下面评论的那样,即使进行了更改,该错误仍然出现在 VS2013 中,因此它实际上不是一种解决方法。

【讨论】:

  • 使用 Visual Studio 2013 我将typedef function&lt;T&gt; function_t; 替换为typedef function&lt;typename remove_pointer&lt;T&gt;::type&gt; function_t;,问题仍然存在。
  • 我刚刚在 Visual Studio 2013 Update 1 中尝试了原始问题和建议的解决方法。但是,两者都无法编译。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-24
  • 1970-01-01
相关资源
最近更新 更多