template function with nested type cannot be deduced

流过昼夜 提交于 2020-01-23 13:26:06

问题


I am working with the SystemC library which requires all user defined types to have a operator<< and sc_trace() function. However the user defined type is actually a nested type inside a template class, because the "nested type" is computed from the template argument specified in the outer class.

template<typename T>
class Block {
    typedef typename transform<T>::value NewType;
public:
    struct SomeType {
        SomeType() {}
        SomeType(T val) : member(val) {}
        NewType member;
    };
};

When I define the operator<< for SomeType like so

template<typename T>
std::ostream& operator<<(std::ostream& os, const typename Block<T>::SomeType& type) {
    return os << type.member;
}

The compiler cannot deduce the call inside the systemC library that does attempt to dump the nested defined type using the streaming operator. Since I rather not touch the library code (outside my control). Would any one of you experts out there know a way to work around this?

And if there is no clean workaround, would you know if the C++11 has a solution for this?


回答1:


I actually found a solution myself. It is referred to as the Barton-Nackman Trick in Vandevoorde/Josuttis.

The key is to avoid using function template. The standard excludes nested type of a dependent template class from template argument deduction. The operator<< and sc_trace function needs to be defined as a friend function in the template class. This way the function is a non-templated function when the template class is instantiated, but with the friend keyword the function takes on the scope of the enclosing namespace.



来源:https://stackoverflow.com/questions/10079941/template-function-with-nested-type-cannot-be-deduced

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!