c++ - 高级 C++ : Copy configuration (object) in a template template class's instance

标签 c++ class templates template-templates

我对模板化类有一个问题,我在这个例子中做了最抽象的。

所以对于具有以下形式的类

template <typename T, template <typename T> class MyFunctor>
class MyMainClass
{
    MyFunctor<T> myInstance;
public:
    setConfigOfMyFunctor<ConfigClass>(const ConfigClass& cfg); //problem is here. How can I write this?
}

我定义了 FunctorClass,我将在 MyMainClass 中将其用作第二个模板参数

template <typename T>
class FunctorClass
{
public:
    ConfigClass<T> cfg;
    int a;
    int b;
    int c;
}

我的配置类在哪里

template <Typename T>
class ConfigClass
{
    T cfgval1;
    T cfgval2;
public:
    void setVals(int cfgVal1, ...);
    //.....
}

如果我创建这个类的对象

int main()
{
    typedef double T;
    MyMainClass<T,FunctorClass> classy;
    ConfigClass<T> config;
    config.setVals(1, 2, ...);
    //so I'm looking for something like the following line (taken from first declaration)
    classy.setConfigOfMyFunctor<ConfigClass>(config); //this is supposed to copy the object config to the FunctorClass's object in MyMainClass.
}

简而言之,我希望将对象 config 复制到 MyMainClass<>::FunctorClass<>::cfg

这可能吗?

如果您需要有关该问题的更多信息,请告诉我。

感谢您的努力。

最佳答案

你不需要参数化 setConfigOfMyFunctor使用任何类型,因为您已经知道接受的配置类型 - ConfigClass<T> .

所以你应该可以这样做:

template <typename T, template <typename T> class MyFunctor>
class MyMainClass
{
    MyFunctor<T> myInstance;
public:
    template<template <typename T> class Config>
    setConfigOfMyFunctor(const Config<T>& cfg) {
        myInstance.cfg = cfg;
    }
}

(如果编译器要求,您需要在某个地方(很可能在 typename 之前)添加关键字 Config<T>)

关于c++ - 高级 C++ : Copy configuration (object) in a template template class's instance,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20304833/

相关文章:

C++ 错误 : operator[] cannot be overloaded

c++ - 在 C++17 中的每个实例化中生成一个新类型

c++ - cv::Mat 从 IplImage 和引用计数创建

c++ - 使用语义操作填充嵌套结构

c++ - CLion:构建程序不会在 cmd 中运行

java - Java 中的类名应该有多独特?

C# 带有成员的静态成员类

c++ - 比函数引用更有效的方法?

c# - 如何将我的代码重组为 C# 中的类?

c++ - 类模板的别名