C++模板 静态成员 定义(实例化)

本文探讨了C++模板中静态成员的定义和初始化问题,包括特化定义、隐式定义以及错误的定义形式。解释了为何某些形式会导致编译错误,并提醒在不同编译单元中定义静态成员可能导致的初始化顺序问题。最后,建议避免特定的定义方式以防止编译问题。
摘要由CSDN通过智能技术生成

提出问题:

如果有这样一个模板:

template <typename T> class Test{
public:
    static std::string info;
};

对于以下若干种定义方式,哪些是对的(通过编译)?

template <> string Test<int>::info("123");
template <typename T> string Test<T>::info("123");
template <typename T> string Test<T>::info;
template <> string Test<int>::info; 
template <> string Test<int>::info();
template <typename T> string Test<T>::info();

为了不影响大家分析判断,我把答案颜色调成比较浅的颜色,下面即是答案:

  1. template <> string Test<int>::info("123");//ok
  2. template <typename T> string Test<T>::info("123");//ok
  3. template <typename T> string Test<T>::info;//ok
  4. template <> string Test<int>::info; //error
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值