gpt4 book ai didi

c++ - 为什么 SFINAE 在这种情况下对我来说工作不正确以及如何解决它?

转载 作者:太空狗 更新时间:2023-10-29 20:09:28 24 4
gpt4 key购买 nike

我试图在 struct A 中留下一个函数 foo(打印 0),如果它的参数有模板方法 isA<void>,另一个(打印 1)如果没有。此代码(减少到下面的最小示例)编译(尝试使用 gcc 6.1.0 和 clang-3.9.0 以及显式 --std=c++14 选项)并运行。

但它会打印 1,但我敢肯定,它会打印 0。我想知道我哪里错了,但真正的问题是:如何使这项工作正确?

请仅使用 C++14 解决方案。

#include <type_traits>
#include <iostream>
#include <utility>

using std::enable_if;
using std::declval;
using std::true_type;
using std::false_type;
using std::cout;

template<int M>
struct ObjectX
{
template<typename C>
bool isA() { return false; }
};

struct XX : ObjectX<23456> {
int af;
};

template <typename ObjType> using has_dep = decltype(declval<ObjType>().template isA<void>());

template <typename, typename = void>
struct has_isa : public false_type {};

template <typename ObjType>
struct has_isa<ObjType, has_dep<ObjType> > : public true_type {};

template<typename ObjType>
struct A
{
template<typename T = void>
typename enable_if<has_isa<ObjType>::value, T>::type
foo() {
cout << "called foo #0" << "\n";
}

template<typename T = void>
typename enable_if<!has_isa<ObjType>::value, T>::type
foo() {
cout << "called foo #1" << "\n";
}
};

int
main()
{
A<XX> axx;
// XX().template isA<void>(); -- to check, that we can call it and it exists
axx.foo();
return 0;
}

最佳答案

这个程序有两个问题。


首先,has_dep<XX>bool .当我们尝试 has_dep<XX> , 添加默认模板参数意味着这真的是 has_dep<XX, void> .但是特化是has_dep<XX, bool> - 这与我们实际查找的内容不符。 bool不匹配 void .这就是为什么 has_dep<XX>false_type .解决方案是 std::void_t ,我建议通读该问答以了解其工作原理。在您的特化中,您需要使用 void_t<has_dep<ObjType>>相反。


其次,这是不对的:

template<typename T = void>
typename enable_if<has_isa<ObjType>::value, T>::type

SFINAE 只发生在替换的直接上下文中,类模板参数不在函数模板替换的直接上下文中。这里的正确模式是:

template <typename T = ObjType> // default to class template parameter
enable_if_t<has_isa<T>> // use the function template parameter to SFINAE
foo() { ... }

修复这两个问题,程序就会按预期运行。

关于c++ - 为什么 SFINAE 在这种情况下对我来说工作不正确以及如何解决它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46119723/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com