[英]Using a template class in multiple classes in C++
Suppose I have 3 classes as shown假设我有 3 个类,如图所示
Instead of the functions in the object class I would like to create a single template function which can take the place of the two functions in the object class. Instead of the functions in the object class I would like to create a single template function which can take the place of the two functions in the object class. The issue I am having is I do not know how to allow the template function to take arguments either of type modifier_1 or type modifier_2.
我遇到的问题是我不知道如何允许模板 function 采用 arguments 类型修饰符_1 或修饰符_2。 Is there a way to do this?
有没有办法做到这一点?
Thank you.谢谢你。
I can think of 3 solutions that might work for what you want.我可以想到 3 种可能适用于您想要的解决方案。
1. 1.
class object : public modifier_1, public modifier_2
{
private:
int x{};
template<class Modifier>
void modify_by_modifier_helper(Modifier mod, int modifier)
{
x += modifier;
}
public:
object() = default;
void modify_by_modifier(modifier_1 mod, int modifier)
{
modify_by_modifier_helper(mod, modifier);
}
void modify_by_modifier(modifier_2 mod, int modifier)
{
modify_by_modifier_helper(mod, modifier);
}
};
2. 2.
#include <type_traits>
class object : public modifier_1, public modifier_2
{
private:
int x{};
public:
object() = default;
template<class Modifier>
void modify_by_modifier(Modifier mod, int modifier)
{
static_assert(std::is_same_v<std::decay_t<Modifier>, modifier_1> ||
std::is_same_v<std::decay_t<Modifier>, modifier_2>,
"Modifier must be modifier_1 or modifier_2")
x += modifier;
}
};
3. 3.
#include <type_traits>
class object : public modifier_1, public modifier_2
{
private:
int x{};
public:
object() = default;
template<class Modifier>
std::enable_if_t<std::is_same_v<std::decay_t<Modifier>, modifier_1> ||
std::is_same_v<std::decay_t<Modifier>, modifier_2>, void>
modify_by_modifier(Modifier mod, int modifier)
{
x += modifier;
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.