c++ - 从具有公共(public)基础的函数对象乘法继承 (C++)

标签 c++ templates multiple-inheritance

我有几个没有成员变量的函数对象。函数对象本质上非常简单。它们都继承自unary_function<>binary_function<> .例如,一些函数对象可能是这样的:

struct key_to_hash_method_1 : public binary_function<int, int, int>
{
  int operator() (int a, int b) const { /* do something */ }
};

template <typename key_to_hash_method>
struct hash_shrink_method_1 : public binary_function<int, int, int>, public key_to_hash_method
{
  int operator() (int a, int b) const { /* do something while utilizing key_to_hash_method */ }
};

/* and more variations of these function objects */

模板类通过将它们作为模板参数作为策略来使用这些函数对象。然后模板类继承自它们:

template <typename hash_method>
class foo : public hash_method 
{
public:
/* do something while using hash_method as well as using the information provided by binary_function<> to selective compile different functions*/
};

当然,为了保持示例简单,就实用性而言,以上内容可能没有多大意义。

为什么我要继承而不是使用组合?只是为了避免空类占用空间。节省的空间是否微不足道不是问题的重点。

从上面的代码可以看出,binary_function<int, int, int>将被继承两次,从而产生警告(在 VC++ 2008 中):

Warning 1   warning C4584: 'hash_shrink_method_1<key_to_hash_method>' : base-class 'std::binary_function<_Arg1,_Arg2,_Result>' is already a base-class of 'key_to_hash_method_1'    c:\visual studio 2008\projects\defaulttemplatearguments\main.cpp    12

现在一般在多重继承中,这是通过虚继承来解决的;在这种情况下我想避免。在这种情况下我该怎么做才能消除警告?

我的直接解决方案是不继承 binary_function<>因为我假设 key_to_hash_method将是 binary_function .这个解决方案感觉有点像无权访问 include guards 或 pragma once 的程序员。陈述。是的,他可以避免两次包含 header ,但他宁愿编译器为他弄清楚。在这种情况下,我也希望如此。


示例代码,如果您想尝试一下:

#include <functional>

using namespace std;

struct key_to_hash_method_1 : public binary_function<int, int, int>
{
  int operator() (int a, int b) const { return a + b; }
};

template <typename key_to_hash_method>
struct hash_shrink_method_1 : public binary_function<int, int, int>, public key_to_hash_method
{
  int operator() (int a, int b) const { return key_to_hash_method::operator()(1, 2) * 5; }
};

template <typename hash_method>
class foo : public hash_method 
{
public:
  int test() 
  { 
    /* in actual code, this function selectively calls other functions 
       depending on whether hash_method is unary or binary */ 
    return hash_method::operator()(5, 6); 
  }
};

int main()
{
  foo<hash_shrink_method_1<key_to_hash_method_1> > f;
  printf("%i\n", f.test());
}

最佳答案

您的 hash_shrink_method_1 不需要直接从 binary_function 继承,因为您假设它的参数类 key_to_hash_method 已经这样做了。如果你想确定,你可以添加一个静态断言(std::is_base_of);不过,如果您已经拥有 C++11,则无论如何都可以取消过时的 binary_function

关于c++ - 从具有公共(public)基础的函数对象乘法继承 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8982430/

相关文章:

C++ 项目到 linux

c++ - SDL_GL_SetAttribute 不设置颜色大小

c++ - 混合双重分派(dispatch)和静态多态性

C++ 模板 : check if a type's destructor can be "ignored"

c++ - 对可变参数模板多继承函数调用的访问不明确

C++:我的右值在哪里?

c++ - 如何在我的网站上编译 C 代码

python - python 类多重继承中的方法重写

C++ 部分模板 模板特化

c++ - 通过使用范围解析避免多重继承引起的歧义