【发布时间】:2011-11-22 09:48:24
【问题描述】:
我们正在尝试重构我们的代码,我们想要的改进之一如下:许多函数有许多参数,但其中许多共享一个公共子集。因此,我们想创建一个将它们分组的结构。问题是有些函数需要一些参数是 const 而有些不是。其中一些函数必须能够调用提供此参数分组结构的这些函数的子集,但有以下限制:被调用函数不能“降级”此结构的常量性(参见以下示例)。实现此结构的所有必需变体可以解决问题,但并不优雅。我们正在研究的一种解决方案是使用模板,例如:
template<class A, class B, class C>
struct my_container
{
A a;
B b;
C c;
};
void foo1(my_container<int, char, float const> & my_cont)
{
}
void foo2(my_container<int const, char, float const> & my_cont)
{
// This should NOT be allowed: we do mind something being const to be treated by the
// called function as non-const.
foo1(my_cont);
}
void foo3(my_container<int, char, float> & my_cont)
{
// This should be allowed: we don't mind something being non-const to be treated by the
// called function as const.
foo2(my_cont);
}
我们的问题是 foo2 在没有编译器抱怨的情况下调用 foo1,而我们希望完全相反。这甚至可以用模板实现吗?有没有其他技术?
【问题讨论】:
-
在我看来,如果 constness 因人而异,也许只是不要尝试对这些论点进行分组。
-
该模板似乎表明您试图将三个相当不相关的值混为一谈? - 如果您有一个真正的相关功能类,我认为通常不会尝试使其部分可修改。例如,您不会特意让函数只修改 Point 实例的 x 坐标而不是 y。如果它很重要,我猜你会将它们作为单独的参数传递。