【问题标题】:function template as member - GCC vs. CLANG作为成员的函数模板 - GCC vs. CLANG
【发布时间】:2016-05-10 11:15:09
【问题描述】:

考虑以下代码:

#include <type_traits>
#include <utility>

template <typename F>
class function
{
public:
//  using function_type = typename std::decay<F>::type;
    using function_type = F;

    function(F func)
        : function_(func)
    {
    }

private:
     function_type function_;
};

template <typename F>
function<F> make_function(F&& func)
{
    return function<F>(std::forward<F>(func));
}

double f1(double)
{
    return 0.0;
}

template <typename T>
T f2(T)
{
    return T();
}

int main()
{
    // works in both cases
    make_function(f1);

    // needs decay (with CLANG)
    make_function(f2<double>);
}

function 类旨在成为任何 Callable 的简单包装器。代码使用 GCC 编译得很好(我从 git 存储库测试了 4.9.2 和 7.0.0 20160427)。但是,clang(3.5.0)抱怨:

function.cpp:17:17: error: data member instantiated with function type 'function_type' (aka 'double (double)')
         function_type function_;
                       ^
function.cpp:55:2: note: in instantiation of template class 'function<double (double)>' requested here
        make_function(f2<double>);

那么这是 GCC 的错误吗?为什么如果变量是参数(在make_function 和构造函数中)它会起作用,但如果它是成员变量则不起作用?衰减(已注释掉)在正确的位置还是应该将其移至make_function?如果我传递一个函数 (f1) 或函数模板的显式实例化 (f2) 为什么会有所不同?

【问题讨论】:

  • 您是否有什么具体原因不想使用std::function?这只是一个学习练习吗?
  • 不应该被make_function(&amp;f2&lt;double&gt;);调用吗?这样它也可以用clang编译好......
  • Clang 错误,已在 3.7 中修复。
  • @JoachimPileborg:是的,我不会避免它,因为上面的代码是性能关键部分。我也想了解这里发生了什么。

标签: c++ c++11 clang++


【解决方案1】:

正如评论者所指出的,这是 Clang 中的一个错误。

代码开始使用 GCC 4.7.1(甚至可能是 4.7?)和 Clang 3.7 进行编译:请参阅 GodBolt

【讨论】:

  • 给你 :) !
猜你喜欢
  • 1970-01-01
  • 2017-08-21
  • 2015-11-12
  • 2020-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-29
相关资源
最近更新 更多