c++ - vector::constructor 的模板参数

标签 c++ templates c++11

我正在尝试编写 GSL 集成例程的小型 C++ 重新实现,作为学习 C++ 元编程的练习项目。我有以下问题。

我已经定义了一些类型特征(使程序可以同时使用 double 和 float )

template<typename T> class IntegrationWorkspaceTraits;

template<> class IntegrationWorkspaceTraits<double>
{
     public:
     typedef double ft; //float_type
     static constexpr ft zero = 0.0;
}; 

template<> class IntegrationWorkspaceTraits<float>
{
    public:
    typedef float ft; //float_type
    static constexpr ft zero = 0.0f;
}; 

现在我有一个使用这个特征的类,看起来像这样

template< typename T, typename AT = IntegrationWorkspaceTraits<T> >    GslIntegrationWorkspace
{
    typedef typename AT::ft   ft;
    typedef typename AT::zero zero;

    public:
    GslIntegrationWorkspace(size_t size);

    private:
    typename std::vector<ft> alist;
}

我的问题是:如何使用特征上定义的零常量来设置成员 vector 的初始值。我的猜测是类似

template<typename T, typename AT> 
GslIntegrationWorkspace::GslIntegrationWorkspace( size_t size ):
alist(size, typename AT::zero),   
{};

但是编译器 g++ 提示“gsl_integration.h:63:42:错误:在没有参数列表的情况下无效使用模板名称‘GslIntegrationWorkspace’”

最好的

最佳答案

zero是值,不是类型!你需要这个:

typedef typename AT::ft ft;
static constexpr ft     zero = AT::zero;

现在您可以使用 GslIntegrationWorkspace<double>::zero等。在构造函数中,您当然只需要 alist(size, zero) .

如果您不使用 ODR 值(例如获取它的地址),您甚至不需要为它定义 - 内联声明和初始化就足够了。

关于c++ - vector::constructor 的模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12548565/

相关文章:

c++ - 通过模板或纯虚拟基类继承进行动态类型文件访问?

c++ - 使用 const 限定符将参数传递给模板函数时出错

c++ - 仅存在声明时不包含类头

c++ - 根据其成员子对象之一的地址计算对象的地址

c++ - 访问节点后出现段错误

c++ - 在 C++ 中生成泊松变量

c++ - 段错误(核心已转储)C++ 面向对象编程

c++ - C++ 编程中的 vector 类

用于执行控制的 c++ 函数代理

C++ 线程不工作, "error: ' 线程'不是 'std' 的成员“