作为成员的函数模板——GCC 与 CLANG
function template as member - GCC vs. CLANG
考虑以下代码:
#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>);
}
class 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
) 会有不同?
正如评论者所指出的,这是 Clang 中的一个错误。
代码开始使用 GCC 4.7.1(甚至可能是 4.7?)和 Clang 3.7 进行编译:请参阅 GodBolt。
考虑以下代码:
#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>);
}
class 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
) 会有不同?
正如评论者所指出的,这是 Clang 中的一个错误。
代码开始使用 GCC 4.7.1(甚至可能是 4.7?)和 Clang 3.7 进行编译:请参阅 GodBolt。