2015-05-07 59 views
0

我想在类模板中为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。

这段代码有什么问题?

回答

2

问题是,在typename test1<T>::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

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

另见: