我有一些代码片段,如下所示,
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
参数实例化了这个函数模板test
,我也无法得到T = const stA
的const版本。
所以问题是我可以在实例化模板时获得const依赖名称吗?
如果答案为否,我还想知道为什么在替换模板参数时会丢弃限定符const
?
如果答案是肯定的,我想要怎么做?
BTW,我在VS2017上测试了上面的代码。
答案 0 :(得分:6)
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
答案 1 :(得分:4)
另外,使用现有特征:
template <typename T>
void test()
{
typename std::conditional<std::is_const<T>::value,
const typename T::stB,
typename T::stB>::type b;
b.func();
/*...*/
}