微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c – 当类被实例化时,类模板的成员是否被实例化?

假设模板类的成员不应该被实例化,除非它们被使用.
但是,这个示例似乎实例化了do_something成员,并且enable_if失败了(如果我们实例化了 – 但是AFAIK,我们没有这样做).

我错过了一些非常基本的东西吗?

#include <string>
#include <boost/utility.hpp>

struct some_policy {
    typedef boost::integral_constant<bool,false> condition;
};

struct other_policy {
    typedef boost::integral_constant<bool,true> condition;
};


template <typename policy>
class test {
   void do_something(typename boost::enable_if<typename policy::condition>::type* = 0) {}
};

int main() {
    test<other_policy> p1;
    test<some_policy>  p2;
}

coliru

解决方法

从C 11 14.7.1 / 1:

The implicit instantiation of a class template specialization causes the implicit
instantiation of the declarations,but not of the deFinitions or default arguments,of the class member functions

所以函数声明被实例化了;它失败,因为它取决于无效类型.

(不幸的是,我没有任何历史版本的标准,但我想象这个规则在C98中是相似的)

原文地址:https://www.jb51.cc/c/114809.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐