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();
/*...*/
}