保存宪法
如果类型是指针,const等,我想要一种保存的方法。请参阅以下内容。
template<typename type>
void test(type t) {
std::cout << "t const? = " << std::is_const<decltype(t)>() << std::endl;
int x = (int) t;
std::cout << "x const? = " << std::is_const<decltype(x)>() << std::endl;
};
int main() {
const int x = 0;
int y = 0;
test<const int>(x);
test<int>(y);
}
>>> t const? = 1
>>> x const? = 0
>>> t const? = 0
>>> x const? = 0
我该如何制作以使函数打印以下内容?换句话说,我如何做到这一点,以便如果模板参数为const,则x也是const?
>>> t const? = 1
>>> x const? = 1
>>> t const? = 0
>>> x const? = 0
我想避免执行以下操作。
// bad
if constexpr (std::is_const<decltype(t)>()) {
// do const cast
} else {
// do non const cast
}
我拥有的具体情况是我有一个const或非const void指针,并希望将其施加给具有类型的指针,同时保存构造。
编辑:这是一个糟糕的例子。您可以使用类型X =(类型)T
。我想要使用类型特征的解决方案,因为这对我来说不是有效的解决方案。
I want a way of preserving if the type is a pointer, const, etc upon a cast. See the following.
template<typename type>
void test(type t) {
std::cout << "t const? = " << std::is_const<decltype(t)>() << std::endl;
int x = (int) t;
std::cout << "x const? = " << std::is_const<decltype(x)>() << std::endl;
};
int main() {
const int x = 0;
int y = 0;
test<const int>(x);
test<int>(y);
}
>>> t const? = 1
>>> x const? = 0
>>> t const? = 0
>>> x const? = 0
How do I make it so that the function prints the following? In other words, how do I make it so that if the template argument is const, x is also const?
>>> t const? = 1
>>> x const? = 1
>>> t const? = 0
>>> x const? = 0
I would like to avoid having to do anything like the following.
// bad
if constexpr (std::is_const<decltype(t)>()) {
// do const cast
} else {
// do non const cast
}
The specific scenario I have is I have a const or non-const void pointer and want to cast it to a pointer with a type, whilst preserving the constness.
Edit: This is a poor example. You can use type x = (type) t
. I wanted a solution using type traits because this isn't a valid solution for me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的示例不是最好说明施放
void*
的实际问题,可能是const
,以相同的constness,因为您可以简单地用type x = t;
替换该行以获取所需的输出。但是,您可以使用一种类型特征:
或如评论中提到的,也许更简单:
Your example isnt the best to illustrate the actual issue to cast a
void*
, possiblyconst
, to someT*
with same constness, because you can simply replace the line withtype x = t;
to get desired output.However, you can use a type trait:
Or as mentioned in comments and perhaps much simpler: