gpt4 book ai didi

c++ - SFINAE 不能防止模棱两可的运算符重载吗?

转载 作者:行者123 更新时间:2023-12-01 14:48:50 28 4
gpt4 key购买 nike

我认为下面的代码会编译,因为冲突的重载是 SFINAEd 了。但是编译器(GCC)说:void Foo<X>::bar(Xd) const' cannot be overloaded .有没有简单的方法来修复它,或者我必须专门研究 Foo ?

#include <type_traits>

struct A{};

template<typename X>
struct Foo {
template<typename Xd=X, typename = std::enable_if_t<std::is_arithmetic<Xd>::value>>
void bar() const {
}

template<typename Xd=X, typename = std::enable_if_t<std::is_same<Xd,A>::value>>
void bar() const {
}
};

int main(){}

最佳答案

来自 the reference对于 std::enable_if:

A common mistake is to declare two function templates that differ only in their default template arguments. This does not work because the declarations are treated as redeclarations of the same function template (default template arguments are not accounted for in function template equivalence).


/*** WRONG ***/
struct T {
enum { int_t,float_t } m_type;
template <typename Integer,
typename = std::enable_if_t<std::is_integral<Integer>::value>
>
T(Integer) : m_type(int_t) {}

template <typename Floating,
typename = std::enable_if_t<std::is_floating_point<Floating>::value>
>
T(Floating) : m_type(float_t) {} // error: treated as redefinition
};


/* RIGHT */
struct T {
enum { int_t,float_t } m_type;
template <typename Integer,
std::enable_if_t<std::is_integral<Integer>::value, int> = 0
>
T(Integer) : m_type(int_t) {}

template <typename Floating,
std::enable_if_t<std::is_floating_point<Floating>::value, int> = 0
>
T(Floating) : m_type(float_t) {} // OK
};

关于c++ - SFINAE 不能防止模棱两可的运算符重载吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59914440/

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