简体   繁体   English

在部分模板专门化中使用decltype

[英]Using decltype in partial template specialization

With the following template and specialization: 使用以下模板和专业化:

template<typename T, typename = void>
struct A {
    void operator()() {
        std::cout << "primary" << std::endl;
    }
};

template<typename T>
struct A<T, decltype(T().f())> {
    void operator()() {
        std::cout << "specialization" << std::endl;
    }
};

used like this: 像这样使用:

struct X {
    bool f() { return false; }
};

int main()
{
    A<X>()();
    return 0;
}

the primary template is resolved, when one would expect partial specialisation to be selected. 当人们期望选择部分特化时,解析主模板。 However, when changed to: 但是,当改为:

template<typename T>
struct A<T, typename std::enable_if<std::is_object<decltype(T().f())>::value>::type> {
    void operator()() {
        std::cout << "specialization" << std::endl;
    }
};

the specialization is chosen. 选择专业化。 Why isn't specialization chosen in the original example? 为什么在原始示例中没有选择专业化?

You have instantiated: 你已经实例化了:

A<X>

Which leverages a default template parameter to become: 利用默认模板参数成为:

A<X,void>

Your specialization, however, is: 但是,你的专长是:

template<typename T>
struct A<T, decltype(T().f())>

Which, for template parameter X becomes: 其中,对于模板参数X变为:

struct A<X, decltype(X().f())>

Which is: 这是:

struct A<X, bool>

So, your specialization is not the correct choice, because A<X,bool> does not specialize A<X,void> . 所以,你的专业化不是正确的选择,因为A<X,bool>不专门化A<X,void>


If you want your specialization to work for all well-formed instances of T().f() , you can use C++17's std::void_t 如果你希望你的专业化适用于所有格式良好的T().f()实例,你可以使用C ++ 17的std::void_t

std::void_t will evaluate to void for any well-formed template parameters passed to it. 对于传递给它的任何格式良好的模板参数, std::void_t将评估为void

template<typename T>
struct A<T, std::void_t<decltype(T().f())>> {
    void operator()() {
        std::cout << "specialization" << std::endl;
    }
};

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

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