【发布时间】: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(&f2<double>);调用吗?这样它也可以用clang编译好...... -
Clang 错误,已在 3.7 中修复。
-
@JoachimPileborg:是的,我不会避免它,因为上面的代码是性能关键部分。我也想了解这里发生了什么。