Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/149.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在实例化模板时,是否可以从const type模板参数中获取与const相关的名称?_C++_C++11_Templates - Fatal编程技术网

C++ 在实例化模板时,是否可以从const type模板参数中获取与const相关的名称?

C++ 在实例化模板时,是否可以从const type模板参数中获取与const相关的名称?,c++,c++11,templates,C++,C++11,Templates,我有一些代码片段,如下所示 struct stA { struct stB { void func() const { std::cout << "const" << std::endl; } void func() { std::cout << "non-cont" << std::endl; } }; }; template <typename T> void t

我有一些代码片段,如下所示

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();
   /*...*/
}
struct stA
{
结构机顶盒
{
void func()常量{std::cout
当然可以。使用帮助器类选择类型

#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>();
}

作为替代方案,使用现有特征:

template <typename T>
void test()
{
   typename std::conditional<std::is_const<T>::value,
                             const typename T::stB,
                             typename T::stB>::type b;
   b.func();
   /*...*/
}
模板
无效测试()
{
类型名称std::条件::类型b;
b、 func();
/*...*/
}

很高兴知道解决此问题的另一种有用方法,谢谢。
template <typename T>
void test()
{
   typename std::conditional<std::is_const<T>::value,
                             const typename T::stB,
                             typename T::stB>::type b;
   b.func();
   /*...*/
}