在我正在进行的某个项目中实现
当我尝试编译这段代码时,似乎找不到我定义的
所以我的问题是,是否可以预期出现这种行为,并且无法使用用户定义类型与
compressed_tuple
类时,遇到了以下问题:即使根据https://en.cppreference.com/w/cpp/utility/apply,似乎无法将此类型的实例传递给 std::apply。
我使用以下代码片段 (godbolt) 很容易地复现了该问题。#include <tuple>
struct Foo {
public:
explicit Foo(int a) : a{ a } {}
auto &get_a() const { return a; }
auto &get_a() { return a; }
private:
int a;
};
namespace std {
template<>
struct tuple_size<Foo> {
constexpr static auto value = 1;
};
template<>
struct tuple_element<0, Foo> {
using type = int;
};
template<size_t I>
constexpr auto get(Foo &t) -> int & {
return t.get_a();
}
template<size_t I>
constexpr auto get(const Foo &t) -> const int & {
return t.get_a();
}
template<size_t I>
constexpr auto get(Foo &&t) -> int && {
return std::move(t.get_a());
}
template<size_t I>
constexpr auto get(const Foo &&t) -> const int && {
return move(t.get_a());
}
} // namespace std
auto foo = Foo{ 1 };
auto f = [](int) { return 2; };
auto result = std::apply(f, foo);
当我尝试编译这段代码时,似乎找不到我定义的
std::get
重载,即使它们应该完全匹配。相反,它试图匹配所有其他重载(如std :: get(pair<T,U>),std :: get(array<...>)等),而没有提及我的重载。我在所有三个主要编译器(MSVC,Clang,GCC)中都得到一致的错误。所以我的问题是,是否可以预期出现这种行为,并且无法使用用户定义类型与
std::apply
一起使用?是否有解决方法?
std
添加函数重载。https://en.cppreference.com/w/cpp/language/extending_std - NathanOliver