gpt4 book ai didi

c++ - 非法用户定义转换?

转载 作者:太空狗 更新时间:2023-10-29 23:09:43 25 4
gpt4 key购买 nike

这是代码和注释:

template<class T>
struct B
{
B(){}

template<class T1> operator T1() { return T1(); }

// define this macro if your compiler fails.
#if (defined USE_MORE_TIDOUS_WAY) // (defined _MSC_VER)
template<class T1> explicit B(B<T1> const& ) {}
template<class T1> operator B<T1>() { return B<T1>(); }
#else
template<class T1> B(B<T1> const& ) {}
#endif


#if 0
////// Explanation:

// firstly, I want to have this convserion ctor :
template<class T1> B(B<T1> const& ) {}

// and the conversion function :
template<class T1> operator T1() { return T1(); }

// but may be T1 is too general, which could hide above
// conversion ctor from some compilers (msvc8~10 fail, gcc 4.4.0~ is ok)

// To overcome such case, add another conversion function :
template<class T1> operator B<T1>() { return B<T1>(); }

// and do not use conversion ctor, while we can still have ctor upon B<T1>
template<class T1> explicit B(B<T1> const& ) {}

#endif
};


// test cases

template<class T> void func(T const&){};

void test()
{
typedef B<int> B1;
typedef B<float> B2;

B1 b1;
B2 b2 = b1; // B1 => B2
b1 = b2; // B2 => B1
b2 = b1; // B1 => B2
func<B1>(b2); // B2 => B1
func<B2>(b1); // B1 => B2
}

int main()
{
test();
}

那么,哪种转换更符合标准且更受青睐?

最佳答案

这个转换的问题:

template<class T1> operator T1() { return T1(); }

是它将 B 转换为任何东西,所以这些将编译:

typedef B<int>      B1;
typedef B<float> B2;

B1 b1;
B2 b2 = b1; // B1 => B2
int x = b1; // compiles
std::string s = b2; // compiles

查看您的测试用例,这些示例需要赋值运算符而不是复制构造函数:

b1 = b2;    // B2 => B1
b2 = b1; // B1 => B2

因此,如果您使用这样的赋值运算符定义您的类,您的测试用例应该可以工作:

template<class T>
struct B
{
B(){}
B& operator=(B&){ return B<T>();};

template<class T1> B(B<T1> const& ) {}
template<class T1> B& operator=(B<T1>&){return B<T>();};

};

关于c++ - 非法用户定义转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4195203/

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