我有一些代码片段如下,
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 版本即使我实例化了这个函数模板test
与 T = 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/