简体   繁体   English

部分专门化c ++中的模板类

[英]Partially specializing template class in c++

I've got a template class: 我有一个模板类:

template <typename T> struct randimpl {
    // default is to not compile, have to pass T to something to get assert
    // evaluated during second phase expansion, is_void is an arbitrary choice.
    static_assert(
        std::is_void<T>::value && false, "random() not implemented for type"
    );
};

This is just a proxy for a random() function that can be overloaded for user-defined types: 这只是random()函数的代理,可以为用户定义的类型重载:

// random function, proxies request through randimpl
template <typename T> T random() {
    return randimpl<T>::random();
}

Which I'm trying to partially specialize for a type _point1d<T> : 我正试图部分专门为类型_point1d<T>

// generate random instances _point1d<T>
template <typename T>
struct randimpl<_point1d<T>> {
    static _point1d<T> random() {
        return _point1d<T>(random<T>());
    }
};

Which as far as I can tell is the appropriate syntax, but when I compile, I get: 据我所知,它是适当的语法,但是当我编译时,我得到:

inc/geometry.h: In static member function ‘static _point1d<T> randimpl<_point1d<T> >::random()’:
inc/geometry.h:287:31: error: expected primary-expression before ‘(’ token
             return _point1d<T>(random<T>());
                               ^
inc/geometry.h:287:40: error: expected primary-expression before ‘>’ token
             return _point1d<T>(random<T>());
                                        ^
inc/geometry.h:287:42: error: expected primary-expression before ‘)’ token
             return _point1d<T>(random<T>());

Is my syntax off? 我的语法是否关闭? This seems like it should work, but I don't understand why it's not accepting it. 这似乎应该有效,但我不明白为什么它不接受它。

The problem is that the static member function's name random hides the global one, it's trying to invoke itself (ie recursive call). 问题是static成员函数的名称random隐藏了全局函数,它试图调用自身(即递归调用)。 But it's not a template and doesn't match how it's called. 但它不是一个模板,与它的调用方式不符。

You can add :: (scope resolution) to specify the global random , eg 您可以添加:: :(范围分辨率)来指定全局random ,例如

// generate random instances _point1d<T>
template <typename T>
struct randimpl<_point1d<T>> {
    static _point1d<T> random() {
        return _point1d<T>(::random<T>());
        //                 ^^
    }
};

LIVE 生活

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM