c++ - 为什么将 T 从外部模板作为默认参数传递给 std::function 会导致编译错误?

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

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

附言。我使用的编译器是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

最佳答案

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

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

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

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

关于c++ - 为什么将 T 从外部模板作为默认参数传递给 std::function 会导致编译错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16007178/

相关文章:

c++ - 是否有可能为 std::map 重载 << 运算符,其中包含对 std:string 和 std::vector<int>?

c++ - 使用 unique_ptr 控制文件描述符

c++ - 如何创建独立的共享库

c++ - 优化循环并避免模板特化中的代码重复

c++ - 使用类模板需要模板参数列表链接列表

c++ - '+' 不能添加两个指针,而只是打印一个 int 和一个显式字符串?

c++ - 从txt文件中读取文本并将其放入静态文本字段,mfc

c++ - 生成 View .obj文件的头

c++ - LNK2001:未解析的外部符号,当试图从另一个 DLL 调用对象的方法时

javascript - 如何将变量传递到 JavaScript 模板中?