英文:
Can you specify class a member as template parameter?
问题
以下是翻译好的部分:
我正在尝试弄清楚你是否可以在模板中执行这个操作:
template <typename T, (这里放置一些内容)>
void DoSomething(T& class_object)
{
std::cout << class_object.(这里放置一些内容) << std::endl;
}
换句话说,你是否可以以某种方式将要访问的成员对象传递给模板?我似乎找不到任何示例。我知道你可以使用宏来实现:
#define DO_SOMETHING(T, member)
void DoSomething(T& class_object)
{
std::cout << class_object.member << std::endl;
}
但我想尽可能使用模板。
<details>
<summary>英文:</summary>
I am trying to figure out if you can do this with templates:
template <typename T, (something here)>
void DoSomething(T& class_object)
{
std::cout << class_object.(something here) << std::endl;
}
In other words, can you pass a member object you would like to access to the template somehow? I can't seem to find any examples anywhere. I know that you could do it with a macro:
#define DO_SOMETHING(T, member)
void DoSomething(T& class_object)
{
std::cout << class_object.member << std::endl;
}
But I'd like to use templates if possible.
</details>
# 答案1
**得分**: 5
以下是翻译好的内容:
```cpp
类似以下内容:
模板 <typename T, auto T::*m>
void 做某事(T& class_object)
{
std::cout << (class_object.*m) << std::endl;
}
[示例](https://godbolt.org/z/rTn471srK)
英文:
Something along these lines:
template <typename T, auto T::*m>
void DoSomething(T& class_object)
{
std::cout << (class_object.*m) << std::endl;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论