2017-08-26 5 views
3

私はC++を学んでいます。私は使用されているConfigurationオブジェクトに応じて、ある方法または別の方法で動作するClassroomクラスを持っています。このような教室オブジェクトを作成するときに、私はコンストラクタでそのConfigurationオブジェクトを渡すことができます。テンプレート引数としてオブジェクトインスタンスを使用するにはどうすればよいですか?

class Classroom { 
private: 
    Configuration conf; 
public: 
    Classroom(Configuration conf_){ 
     conf = conf_; 
    } 
    /** more member functions that use conf **/ 
}; 

しかし、私は、私はそれのためのテンプレートを使用することができれば、それは涼しいだろうと思いました。 Classroomオブジェクトの作成時にConfigurationオブジェクトがテンプレートの引数として渡されます。これは私が思い付いたものですが、それは動作しません:

template<Configuration &conf> 
class Classroom { 
    int doSomething(int n){ 
     // member function that uses data in Configuration object 
     return n + conf.config_1; 
    } 
}; 

struct Configuration { 
public: 
    int config_1; 
}; 

int main() { 
    Configuration conf; 
    conf.config_1 = 95; 
    Classroom<conf> myClassroom;// doesn't work 
} 

それは言う:エラー:「confに」の値は、定数式では使用できません。

私には何が欠けていますか?

+0

テンプレートのインスタンス化は、コンパイラによって行われます。だから、テンプレート引数として渡すものは、コンパイル時に知られているはずです –

+0

キーワード 'typename or class'がありません。 – Raindrop7

+5

_ "テンプレートを使うことができれば、もっとクールだと思っていました。"合理的なユースケースを1位にしてください。 – user0042

答えて

1

のようなものです。あなたがそれをしようとしている方法は有効ではありません。それはストレージの問題です。

あなたの周りに複数の構成が必要な場合は、クラステンプレートの静的メンバとしてそれを定義したり、Configuration Sのグローバル配列を定義することができます:あなたは、単一のインスタンスに固執することができれば、

struct Configuration { 
    int config_1; 
}; 

template<int> 
struct Accessor { 
    static Configuration configuration; 
}; 

template<int N> 
Configuration Accessor<N>::configuration; 

template<Configuration &conf> 
class Classroom { 
    int doSomething(int n){ 
     return n + conf.config_1; 
    } 
}; 

int main() { 
    Accessor<1>::configuration.config_1 = 95; 
    Classroom<Accessor<1>::configuration> myClassroom; 
    (void)myClassroom; 
} 

struct Configuration { 
    int config_1; 
}; 

Configuration conf; 

template<Configuration &conf> 
struct Classroom { 
    int doSomething(int n){ 
     return n + conf.config_1; 
    } 
}; 

int main() { 
    conf.config_1 = 95; 
    Classroom<conf> myClassroom; 
    myClassroom.doSomething(42); 
} 

他の解決策も可能ですが、私はあなたが考えていると確信しています。


wandbox上の例uprunningを参照してください。

1

テンプレートパラメータは、コンパイル時に既知のリテラルまたはリテラルまたは列挙型の制限されたセットであることを意味します。

だからできません。あなたがが何ができるか


あなたはいくつかの制限を行うことができ

template<typename ConfType> 
class Classroom { 
    const ConfType& conf_; 
public: 
    // Provide a constructor that takes a reference to the Configuration type 
    Classroom(const ConfType& conf) : conf_(conf) {} 
    int doSomething(int n){ 
     // member function that uses data in Configuration object 
     return n + conf.config_1; 
    } 
}; 

struct Configuration { 
public: 
    int config_1; 
}; 

int main() { 
    Configuration conf; 
    conf.config_1 = 95; 
    Classroom<Configuration> myClassroom(conf); 
} 
+0

[あなたが知っている...](https://wandbox.org/permlink/2LTZEOWI2Ns1jMwl)。 – skypjack

+0

あなたは[複数の設定](https://wandbox.org/permlink/jg0jDSEqQPW0jqf8)を持つことさえできます。 – skypjack

関連する問題