将使用include的程序转换为使用模板的程序 [英] Convert a program that uses includes to one using templates

查看:168
本文介绍了将使用include的程序转换为使用模板的程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个示例来显示我使用的语言功能,真实情况不是那么简单。 include文件包含两次,每个类一次。即使文本是相同的,底层类型也不同。在实际情况下,根据类别,一些变量具有比其他变量更多的初始化。

I have created an example to show the language features I am using, the real case is not as simple. The include file is included twice, once for each class. Even though the text is the same, the underlying types are different. In the real case some variables have more initialization than others depending on the class.

工作程序

ex1。 cpp

#include <iostream>

class one {
public:
   one(int a1,int b1) : a(a1), b(b1) {}
   int a,b;
#include "ex1.h"
};

class two {
public:
   two(double a1,double b1) : a(a1), b(b1) {}
   double a,b;
#include "ex1.h"
};

int main()
{
   one c1(1,2);
   two c2(3.4,5.7);
   c1.f();
   c2.f();
   return 0;
}

ex1.h

void f()
{
    std::cout << ( a + b ) << std::endl;
}



我希望将此更改为使用模板的程序,我收到一个编译错误。

I was hoping to change this to a program that uses templates as follows, but I get a compile error.

ex2.cpp

#include <iostream>

class one {
public:
   one(int a1,int b1) : a(a1), b(b1) {}
   int a,b;
   void f();
};

class two {
public:
   two(double a1,double b1) : a(a1), b(b1) {}
   double a,b;
   void f();
};

template<typename X>
void X::f()
{  
    std::cout << ( a + b ) << std::endl;
}  

int main()
{
   one c1(1,2);
   two c2(3.4,5.7);
   c1.f();
   c2.f();
   return 0;
}

错误消息为错误:无效使用模板类型参数'X'

The error message is error: invalid use of template type parameter 'X'

推荐答案

CRTP 拯救:

template<class D>
struct f_support {
  void f() {
    // does not block all errors, but catches some:
    static_assert( std::is_base_of< f_support, D >::value, "CRTP failure" );
    auto* dis = static_cast<D*>(this);
    std::cout << ( dis->a + dis->b ) << std::endl;
  }
};

然后:

class one: public f_support<one> {

...

class two: public f_support<two> {

...

f_support< D> 的实现移动到.cpp文件中,但这是一个麻烦。

You could move the implementation of f_support<D> into a .cpp file, but that is a hassle.

这篇关于将使用include的程序转换为使用模板的程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆