【发布时间】:2018-07-21 03:38:48
【问题描述】:
另一个类型的问题“谁在 g++ 和 clang++ 之间是对的?”供 C++ 标准专家使用。
假设我们希望将 SFINAE 应用于变量模板以仅在模板类型满足特定条件时启用该变量。
例如:当(且仅当)模板类型具有带有给定签名的foo() 方法时,启用bar。
通过具有默认值的附加模板类型使用 SFINAE
template <typename T, typename = decltype(T::foo())>
static constexpr int bar = 1;
适用于 g++ 和 clang++ 但有一个问题:可以被劫持解释第二种模板类型
所以
int i = bar<int>;
在哪里给出编译错误
int i = bar<int, void>;
编译没有问题。
所以,由于我对 SFINAE 的无知,我尝试启用/禁用同一变量的类型:
template <typename T>
static constexpr decltype(T::foo(), int{}) bar = 2;
惊喜:这对 g++ 有效(编译),但 clang++ 不接受它并给出以下错误
tmp_003-14,gcc,clang.cpp:8:30: error: no member named 'foo' in 'without_foo'
static constexpr decltype(T::foo(), int{}) bar = 2;
~~~^
像往常一样,问题是:谁是对的? g++ 还是 clang++ ?
换句话说:根据 C++14 标准,SFINAE 可以用于变量模板的类型?
下面是一个完整的例子
#include <type_traits>
// works with both g++ and clang++
//template <typename T, typename = decltype(T::foo())>
//static constexpr int bar = 1;
// works with g++ but clang++ gives a compilation error
template <typename T>
static constexpr decltype(T::foo(), int{}) bar = 2;
struct with_foo
{ static constexpr int foo () { return 0; } };
struct without_foo
{ };
template <typename T>
constexpr auto exist_bar_helper (int) -> decltype(bar<T>, std::true_type{});
template <typename T>
constexpr std::false_type exist_bar_helper (...);
template <typename T>
constexpr auto exist_bar ()
{ return decltype(exist_bar_helper<T>(0)){}; }
int main ()
{
static_assert( true == exist_bar<with_foo>(), "!" );
static_assert( false == exist_bar<without_foo>(), "!" );
}
【问题讨论】:
-
您确定您的第一个 sn-p 运行的是 sfinae 而不是硬错误吗?如果是函数模板,它不会...
-
我希望
T::foo()没有返回类型R带有重载的operator,(R,int)... -
我的意思是
template <class T, decltype(T::foo ()) * = nullptr>会调用 sfinae 这个我不太确定... -
@W.F. - 你让我怀疑。不确定是否理解您的问题。您的意思是:如果没有替代方案,我们可以将其定义为 SFINAE 吗?在这种情况下,是的,我想我们可以定义另一个镜面反射变量
bar,当(且仅当)第一个未定义时才定义。 -
对“直接上下文”没有明确定义的问题再次引起人们的注意。没有人确切知道。 (参见核心问题 1844。)
标签: c++ templates c++14 sfinae template-variables