簡體   English   中英

在實例化模板時,我可以從const類型模板參數中獲取const依賴名稱嗎?

[英]Can I get a const dependent name from a const type template argument when instantiating a template?

我有一些代碼片段如下,

struct stA
{
    struct stB
    {
        void func() const { std::cout << "const" << std::endl; }
        void func()       { std::cout << "non-cont" << std::endl; }
    };
};

template <typename T>
void test()
{
   typename T::stB b;//can I get a const version of b?
   b.func();
   /*...*/
}

在我的測試中,我發現即使用T = const stA參數實例化這個函數模板test ,我也無法獲得b的const版本。

所以問題是我可以在實例化模板時獲得const依賴名稱嗎?

如果答案為否,我還想知道為什么在替換模板參數時會丟棄限定符const

如果答案是肯定的,我想怎么樣?

順便說一下,我在VS2017中測試了上面的代碼。

 typename T::stB b;//can I get a const version of b? 

當然。 使用幫助程序類來選擇類型。

#include <iostream>

struct stA
{
   struct stB
   {
      void func() const
      {
         std::cout << "const" << std::endl;
      }
      void func()
      {
         std::cout << "non-cont" << std::endl;
      }
   };
};

// Helper class to select the type.
// Base version provides a non-const type.
template <typename T> struct type_selector
{
   using type = typename T::stB;
};

// Specialization provides a const type.
template <typename T> struct type_selector<const T>
{
   using type = const typename T::stB;
};


template <typename T>
void test()
{
   typename type_selector<T>::type b;
   b.func();
}

int main()
{
   test<stA>();
   test<const stA>();
}

輸出:

non-cont
const

作為替代方案,使用現有特征:

template <typename T>
void test()
{
   typename std::conditional<std::is_const<T>::value,
                             const typename T::stB,
                             typename T::stB>::type b;
   b.func();
   /*...*/
}

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM