不能推导带有嵌套类型的模板函数 [英] template function with nested type cannot be deduced

查看:124
本文介绍了不能推导带有嵌套类型的模板函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用SystemC库,该库要求所有用户定义的类型都必须具有运算符.和sc_trace()函数.但是,用户定义的类型实际上是模板类内部的嵌套类型,因为嵌套类型"是根据外部类中指定的模板参数计算得出的.

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

当我定义运算符时<<像这样的SomeType

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

编译器无法推断出确实尝试使用流运算符转储嵌套定义的类型的systemC库中的调用.因为我宁愿不触摸库代码(在我的控件之外).你们中的任何一位专家都知道解决此问题的方法吗?

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?

如果没有干净的解决方法,您是否知道C ++ 11是否有解决方案?

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

推荐答案

我实际上自己找到了解决方案.在Vandevoorde/Josuttis,它被称为Barton-Nackman Trick.

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

关键是要避免使用功能模板.该标准从模板参数推论中排除了依赖模板类的嵌套类型.运算符<<和sc_trace函数需要在模板类中定义为朋友函数.这样,当实例化模板类时,该函数是一个非模板函数,但是使用friend关键字,该函数将承担封闭名称空间的范围.

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.

这篇关于不能推导带有嵌套类型的模板函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆