c++ - 我可以在实例化模板时从 const 类型模板参数中获取 const 相关名称吗?

标签 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 test()
{
   typename T::stB b;//can I get a const version of b?
   b.func();
   /*...*/
}

在我的测试中,我发现我无法获得 b 的 const 版本即使我实例化了这个函数模板testT = const stA争论。

所以问题是我可以在实例化模板时获得一个 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

关于c++ - 我可以在实例化模板时从 const 类型模板参数中获取 const 相关名称吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48334296/

相关文章:

wpf - 在WPF中动态添加网格和控件

c++ - 在Windows中将数据分配到特定地址?

c++ - 覆盖代理类 c++ 的 std::swap

c++ - 将推断类型传递给 std::find_if lambda 函数

c++ - <未解析的重载函数类型> 调用二元谓词

C++限制模板模板中的内部类型

c++ - 在二进制 {0, 255} 图像中找到中值时消除分支

c++ - 在 decltype 中使用 this 指针

c++ - 对象 vector 的初始化列表

c++ - 嵌入式 C++11 代码——我需要 volatile 吗?