开发者社区> 问答> 正文

C++ 多个模板中其中一个的模板特化

头文件 mycomputationclass.h

#pragma once
template<typename numberType, bool increaseByOne>
class MyComputationClass
{
   numberType a = 1;
   numberType b = 2;
   numberType compute();
};

#include #include mycomputationclass.hpp

hpp:

#pragma once
#include mycomputationclass.h

template<typename numberType, bool increaseByOne>
numberType MyComputationClass<numberType, increaseByOne>::compute()
{
   return a + b;
}
template<typename numberType>
numberType MyComputationClass<numberType, true>::compute()
{
   return a + b + 1;
}

error:

error: invalid use of incomplete type ‘class MyComputationClass<numberType, true>’
 numberType MyComputationClass<numberType, true>::compute()
                                                          ^

我发现与模板特化相关的所有主题都仅使用一个模板。 有人可以在这里帮我吗?

问题来源:stackoverflow

展开
收起
禹果 2020-03-21 00:14:36 886 0
1 条回答
写回答
取消 提交回答
  • 首先,请参阅 为什么只能在头文件中实现模板(阿里云社区地址)

    为什么只能在头文件中实现模板(stackoverflow地址) 现在,您的问题并非来自上述问题,但是,您仍应需要考虑是否要在cpp文件中实现模板。 我怀疑你没有。

    无论如何,您要问的问题是您试图定义一个尚未模板特化的专门类模板的方法。

    下面有两个选择。 - 您可以特化类模板,重复整个过程

    template<typename numberType>
    class MyComputationClass<numberType, true>
    {
       numberType a = 1;
       numberType b = 2;
       numberType compute();
    };
    
    • 您可以使用所有通用代码创建类模板,并派生类模板仅包含您需要特化的部分
    • 在C++ 17 中你可以使用 if constexpr :
    template<typename numberType, bool increaseByOne>
    numberType MyComputationClass<numberType, increaseByOne>::compute()
    {
        if constexpr (increateByOne)
            return a + b + 1;
        else
            return a + b;
    }
    
    • 在C ++ 20中,您可以使用require子句:
    template<typename numberType, bool increaseByOne>
    class MyComputationClass
    {
       numberType a = 1;
       numberType b = 2;
       numberType compute() requires increaseByOne
       {
           return a + b + 1;
       };
        numberType compute() requires (!increaseByOne)
       {
           return a + b;
       };
    };
    

    回答来源:stackoverflow

    2020-03-21 00:22:03
    赞同 展开评论 打赏
问答分类:
C++
问答地址:
问答排行榜
最热
最新

相关电子书

更多
使用C++11开发PHP7扩展 立即下载
GPON Class C++ SFP O;T Transce 立即下载
GPON Class C++ SFP OLT Transce 立即下载

相关实验场景

更多