用于泛型类型上的泛型操作的SFINAE

SFINAE for generic operation on generic type

本文关键字:操作 SFINAE 泛型 用于 泛型类型      更新时间:2023-10-16

我有

  • 一个类Value,它可以用不同的类型(Foo,Bar,int,…)构造。

  • classValue应该具有类似<lt;,==<,。。。以底层类型进行

  • 我添加了运算符<lt外部类定义。

我必须使用以下代码:

#include <iostream>
struct Foo {
};
struct Bar {
};
struct Value {
template<typename T>
Value(T) {
}
};
std::ostream &operator<<(std::ostream &os, const Bar &) {
return os << "Barn";
}
std::ostream &operator<<(std::ostream &os, const Value &value) {
auto visitor = [&](auto a) -> decltype(os << a) {
return os << a;
};
// Works
visitor(Bar{});
// Infinity call of this function with Value.
visitor(Foo{});
return os;
}
int main() {
std::cout << Value(1);
return 0;
}

活生生的例子。

问题是:如果底层类型没有实现运算符<lt;,运算符<lt;从被称为递归无穷大。我想得到一个编译器错误,比如调用运算符<lt;(std:ostream&,const-Value&)将SFINAE用于我的访问者模式(此处未显示)。

我需要的是:

[&](auto a) -> std::enable_if_t<addressof?(os << a) != addressof?(os << Value{})>::value> {
return os << a;
};

如果函数相同,则禁用此lambda。这可能吗?

没有价值的解决方案:

  • 使值显式
  • 禁用Foo的Value构造

您可以添加一个包装器来强制执行一个转换:

template <typename T>
struct OneConversion
{
OneConversion(const T& t) : t(t) {}
operator const T&() const {return t;}
const T& t;  
};
template <typename T>
struct isOneConversion : std::false_type {};
template <typename T>
struct isOneConversion<OneConversion<T>> : std::true_type {};
struct Value {
template<typename T, std::enable_if_t<!isOneConversion<T>::value>* = nullptr>
Value(T) {}
};
std::ostream &operator<<(std::ostream &os, const Value &value) {
auto visitor = [&](auto a) -> decltype(os << OneConversion<decltype(a)>(a)) {
return os << OneConversion<decltype(a)>(a);
};
// Works
visitor(Bar{});
visitor(Foo{}); // Error as expected.
return os;
}

演示

在不修改std::ostream &operator<<(std::ostream &os, const Value &value)的签名的情况下,我们可以检查为a在lambda中被推导为的类型调用operator<<的尝试是否格式正确:

auto visitor = [&](auto a) -> decltype(
static_cast<std::ostream&(*)(std::ostream&, const decltype(a)&)>(&operator<<)
(os, a)
)
{
return os << a;
};

Bar一起工作,与Foo一起失败,并显示错误消息:

error: invalid static_cast from type '<unresolved overloaded function type>' to type 'std::ostream& (*)(std::ostream&, const Foo&

Demo

您可以替换

std::ostream &operator<<(std::ostream &os, const Value &value)
{
// ...
}

带有

template <typename T, typename = std::enable_if_t<std::is_same_v<T, Value>>>
std::ostream &operator<<(std::ostream &os, const T &value)
{
// ...
}

您仍然可以使用它打印Value对象,但不需要隐式转换。

将它放入您的代码中会导致它在visitor(Foo{});失败,并出现以下错误,这似乎正是您想要的。

...
main.cpp:29:12: error: no match for call to '(operator<<(std::ostream&, const T&) [with T = Value; <template-parameter-1-2> = void; std::ostream = std::basic_ostream<char>]::<lambda(auto:1)>) (Foo)'
visitor(Foo{});
~~~~~~~^~~~~~~
...