【问题标题】:Overloading operator on member enum of class template类模板成员枚举上的重载运算符
【发布时间】:2015-05-07 19:46:36
【问题描述】:

我想为类模板中的enum 重载operator |

这是一个最小的例子:

#include <iostream>
using namespace std;

template <class T>
struct test1 {
    enum test2 {
        test3, test4
    };
};

template <class T>
typename test1<T>::test2 operator | (typename test1<T>::test2 f1, typename test1<T>::test2 f2) {
    return static_cast<typename test1<T>::test2>(
        static_cast<unsigned>(f1) | static_cast<unsigned>(f2)
    );
}

int main() {
    test1<int>::test2 flags = test1<int>::test3 | test1<int>::test4; // error here
}

Live example.

编译器在此代码中显示以下诊断:

In function 'int main()':
error: invalid conversion from 'int' to 'test1<int>::test2' [-fpermissive]
  test1<int>::test2 flags = test1<int>::test3 | test1<int>::test4;

我还尝试使用 LLVM 6.1.0 编译此代码。

这段代码有什么问题?

【问题讨论】:

    标签: c++ templates overloading


    【解决方案1】:

    问题是typename test1&lt;T&gt;::test2中,模板参数Tnon-deduced context中,所以C++不能从函数参数的类型推导出它的模板参数。

    您可以通过显式实例化函数模板来看到这一点:

    test1<int>::test2 flags = operator | <int> (test1<int>::test3, test1<int>::test4);
    

    DEMO

    或者通过使用类模板的非模板友元函数:

    template <class T>
    struct test1 {
        enum test2 {
            test3, test4
        };
        friend test2 operator | (test2 f1, test2 f2) {
            return static_cast<test2>(
                static_cast<unsigned>(f1) | static_cast<unsigned>(f2)
            );
        }
    };
    
    int main() {
        test1<int>::test2 flags = test1<int>::test3 | test1<int>::test4;
    }
    

    DEMO

    另见:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-04
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      相关资源
      最近更新 更多