非法用户定义转换?

时间:2010-11-16 14:32:35

标签: c++

这是代码和评论:

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();
}

那么,哪种转换更符合标准并且更受欢迎?

1 个答案:

答案 0 :(得分:1)

此次转化的问题:

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>();};

};