gpt4 book ai didi

c++ - MSVC:具有模板化转换运算符和多重继承的错误

转载 作者:行者123 更新时间:2023-12-02 09:59:16 25 4
gpt4 key购买 nike

我有以下代码无法与MSVC一起编译。使用gcc,clang和icc可以正常编译。我想这是个错误,对不对?
您有/知道一些解决方法吗?

#include <type_traits>

struct A
{
template <
typename C
,typename = std::enable_if_t<std::is_same_v<C, int>>
>
operator C() const{
return 12;
}
};

struct B
{
template <
typename C
, typename = std::enable_if_t<std::is_same_v<C, char>>
, typename F = int
>
operator C() const
{
return 'A';
}
};

struct AB : A, B
{
};

int main(){
AB ab;
int i = ab;
char c = ab;
}
错误文本为:
example.cpp

<source>(34): error C2440: 'initializing': cannot convert from 'AB' to 'char'

<source>(34): note: No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

Compiler returned: 2
我已经向Microsoft发布了 bug report
godbolt上查看

最佳答案

这似乎确实是MSVC中的错误。在运算符(operator)模板推导过程中似乎不考虑最后一个基数。对于前。

struct AB : A, B // -> only A's templated operator considered
struct AB : B, A // -> only B's templated operator considered
在您的情况下,您可以删除模板化的运算符并直接使用类型( Live)(在这种情况下,使用模板没有多大意义):
#include <type_traits>

struct A
{
operator int() const{ return 12;}
};

struct B
{
operator char() const { return 'A'; }
};

struct AB : A, B
{
};

int main(){
AB ab;
int i = ab;
char c = ab;
}
或者您可以改为使用类模板,例如( Live):
#include <type_traits>

template <typename T, typename = std::enable_if_t<std::is_integral_v<T>>>
struct A
{

operator T() const{
return 12;
}
};

template <typename T, typename = std::enable_if_t<std::is_same_v<T,char>>>
struct B
{
operator T() const
{
return 'A';
}
};

struct AB : A<int>, B<char>
{
};

int main(){
AB ab;
int i = ab;
char c = ab;
}
或者您可以在单个类( Live)中重载模板化歌剧 Actor :
struct A
{
template <
typename C
, typename = std::enable_if_t<std::is_same_v<C, int>>
>
operator C() const {
return 12;
}

template <
typename C
, typename = std::enable_if_t<std::is_same_v<C, char>>
, typename F = int
>
operator C() const
{
return 'A';
}
};


struct AB : A
{
};

int main() {
AB ab;
int i = ab;
char c = ab;
}

关于c++ - MSVC:具有模板化转换运算符和多重继承的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63523244/

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