C++11 Initialization of template class member in template class

I have a bunch of template classes, based on an enumeration type. Here is the source code:

#include <iostream> // An enum type enum class ENUMR : unsigned char { SYSTEM1, SYSTEM2, UNKNOWN }; // template class; will later be specialized based on ENUMR enumerators template<ENUMR S> class System {}; // specialized System class, for enumerator SYSTEM1 template<> class System<ENUMR::SYSTEM1> { private: static constexpr char identifier { 'G' }; }; // An observation class recorded from a certain System instance template<ENUMR Sys,short int Freq> class Obs { public: Obs(): m_system {System<Sys> {} }, // does not work m_frequency {Freq} {}; //{ // m_system = System<Sys> {}; // works //} private: System<Sys> m_system; short int m_frequency; }; // dummy code to test the template classes int main () { System<ENUMR::SYSTEM1> s1; System<ENUMR::UNKNOWN> s2; System<ENUMR::SYSTEM1> s3 (System<ENUMR::SYSTEM1>); Obs<ENUMR::SYSTEM1, 1> obs; std::cout <<"\n"; return 0; }

Initialization of the member (template) variable Obs::m_system produces a compile-time error, when performed as m_system {System<Sys> {} }. However, when the same variable is initialized as m_system = System<Sys> {}; the source codes gets compiled (the respective lines in the source code above are commented). Does that mean that the assignment operator works, but the copy constructor fails? If so, why? When compiled against the gcc version 4.8.3 i get the following error message:

test.cpp: In instantiation of ‘Obs<Sys, Freq>::Obs() [with ENUMR Sys = (ENUMR)0u; short int Freq = 1]’: test.cpp:43:28: required from here test.cpp:25:22: error: too many initializers for ‘System<(ENUMR)0u>’ m_frequency {Freq} {};

-------------Problems Reply------------

System<ENUMR::SYSTEM1> is an aggregate, so the mem-initializer m_system { System<Sys>{} } performs aggregate-initialization. Since System<ENUMR::SYSTEM1> has no corresponding member - indeed it has no members at all - for the corresponding initializer System<Sys>{}, you get the error indicating there are too many initializers.

If System<ENUMR::SYSTEM1> were not an aggregate, the effect of that mem-initializer would be to direct-list-initialize m_system from a value-initialized temporary of the same type. Since the move/copy constructors are defaulted, you could achieve the equivalent effect for both the aggregate and non-aggregate case by directly value-initializing m_system with an empty brace initializer: m_system {}. (DEMO)

If you change

m_system{ System<Sys>{} },
m_frequency{ Freq }


m_system( System<Sys>{} ),
m_frequency( Freq )

it will compile. Note however, that the first initializer creates a default constructed temporary, and then uses the copy constructor to initialize the member. Since you want m_system to be default constructed, that initializer can be omitted.

Category:templates Views:0 Time:2017-09-11

Related post

  • Initialization of array-of-classes member of a class 2012-02-22

    I want to initialize array-of-classes member of a class const int count = 5; class In { float rate; public: In( int index ) { rate = index / count; } }; class Out { In ins[count]; public: Out() : /* ??? */ { } }; Can I obtain index of instance of In

  • Enforce use of scope resolution operator when accessing base class member from derived class 2010-10-08

    I have a class Derived which is derived from class Base. In Derived's function, I can access protected members of Base. E.g., I can do this. class Base { protected: int i; } class Derived : class Base { void process() { i = 5; } } My question is, is

  • specifying type of a class member in template function 2011-05-31

    I have this template function: template <class P> double Determinant(const P & a, const P & b, const P & c) { return (b.x-a.x)*(c.y-a.y) - (c.x-a.x)*(b.y-a.y); } but I want to avoid forcing the return type to double all the time --

  • Pointer to class member as template parameter 2011-07-30

    Is it possible to have non-type template parameter which is actually a pointer to a class member? What I'm looking to do is something like the following: struct Person { Dog dog; }; template <?? ptr> struct Strange { // ... }; typedef Strange

  • Invalid template dependent member function template deduction - thinks I'm trying to use std::set 2012-05-03

    I have a class template which inherits from a base class template. The base class template has a data member with a member function template which I want to call from within my super class. I know that in order to disambiguate the call to the member

  • Static local in class member function survives class reallocation? 2009-08-29

    class Foo { public: void bar(); }; void Foo::bar() { static int n = 0; printf("%d\n", n++); } int main(int argc, char **argv) { Foo *f = new Foo(); f->bar(); delete f; f = new Foo(); f->bar(); delete f; return 0; } Does n reset to 0 after delet

  • How to restrict access to nested class member to enclosing class? 2009-11-03

    Is it possible to specify that members of a nested class can be accessed by the enclosing class, but not other classes ? Here's an illustration of the problem (of course my actual code is a bit more complex...) : public class Journal { public class J

  • C++ Access derived class member from base class pointer 2010-03-12

    class Base { public: int base_int; }; class Derived : public Base { public: int derived_int }; Base* basepointer = new Derived(); basepointer-> //Access derived_int here, is it possible? If so, then how? --------------Solutions------------- No, yo

  • accessing a base class member in derived class 2011-03-01

    i have a simple class as below class A { protected: int x; }; class B:public A { public: int y; void sety(int d) { y=d; } int gety(){ return y;} }; int main() { B obj; obj.sety(10); cout<<obj.gety(); getch(); } since the variable A::x has prote

  • Check if class member is a class object 2011-07-19

    I have a class whose member is another class object among other members. I would like to know how to determine whether the this field is a java class (user defined). That is, I have something like this: The user passes the name of a java class. If th

  • Initialize static std::map member inside templated class? 2012-01-03

    Here is a code snippet from my project: template<typename Second, typename First = const UINT64> class Event : virtual public id_manager<> { friend class EventHandler; typedef std::map<First, EventHandler> eventMap; static eventMap

  • C++: Trying to import class as a class member into another class, does not copy properly 2009-05-08

    Thanks to all that responded to my previous thread. There is still a problem with this simple program that I would like to solve. I am trying to import one class into another as a member object. The output of this program is confusing, though. As a t

  • Accessing overridden base class member from derived class object 2010-10-06

    I have two classes: class A { public: int i; }; class B : public A { public: int i; }; Suppose that I created an object for class B B b; Is it possible to access A::i using b? --------------Solutions------------- Is it possible to access A::i using b

  • Initializing class member arrays in class constructors? 2011-11-10

    Here's my header file with the array Data that my teacher wants to initialize in Heap's constructor. #ifndef HEAP_H #define HEAP_H class Heap { private: int Data [100]; int Parent(int); int RightChild(int); int LeftChild(int); void Heapify(int*, int)

  • Accessing Sub class member from base class in objective c 2012-04-20

    i tried to access the subclass member variable from base class. But i can't access it. It returns a null value.. for eg.. I have baseclass classA and Subclass ClassB. i tried to access the classB member variable say x from base class ClassA. but it r

  • Using valid STATIC member function of class that can't be installed 2009-11-02

    I have following piece of code: It compiles without problems under gcc-3.4, gcc-4.3, intel compiler, but fails under MSVC9. MSVC tells "use of undefined type c_traits<C>, while compiling class template member function void foo<C>::go(void

  • Member function templates cannot be declared virtual - From Addison Wesley: C++ Templates 2011-04-21

    From Addison Wesley: C++ Templates Member function templates cannot be declared virtual. This constraint is imposed because the usual implementation of the virtual function call mechanism uses a fixed-size table with one entry per virtual function. H

  • Can I specialize a class template with an alias template? 2011-10-18

    Here's a simple example: class bar {}; template <typename> class foo {}; template <> using foo<int> = bar; Is this allowed? --------------Solutions------------- $ clang++ -std=c++0x test.cpp test.cpp:6:1: error: explicit specializat

  • Using typedefs of a non-template derived class in the base class when using CRTP 2014-09-04

    I'm using CRT pattern and want the base class to see typedefs from the derived class. In this post @James McNellis suggested to do that using base_traits class and it works fine. But in the case described in that post the derived class itself is a te

  • public class member visible to descendents 2009-06-02

    I have been getting a lot of traction from a builder pattern as a public class member of another class: public class Part { public class Builder { public string Name { get; set; } public int Type { get; set; } public Part Build() { return new Part(Na

  • How can I store a boost::bind object as a class member? 2011-10-13

    I'm writing an application that uses boost::asio. Asio's async_receive (or async_read) is invariably shown using a boost::bind object given for callback: boost::asio::async_read(socket_, boost::asio::buffer(read_msg_.data(), chat_message::header_leng

  • definition of static class function outside of class definition 2012-02-28

    Consider the followin simple class definition - // file A.h #include <iostream> class A { public: static int f(); static const int aa; }; // file A.cpp #include "a.h" using namespace std; const int A::aa = 10; int A::f() { return A::aa; } And t

  • Initializing template base-class member types in derived-class initializer lists 2009-07-13

    Here is some code outlining a problem I've been wrestling with. The final problem (as far as g++ is concerned at the moment) is that: "error: 'Foo-T' was not declared in this scope" when performing the Bar::Bar(...) constructor routine. Otherwise, th

  • Initialize static member of template inner class 2010-02-20

    I have problem with the syntax needed to initialize a static member in a class template. Here is the code (I tried to reduce it as much as I could): template <typename T> struct A { template <typename T1> struct B { static T1 b; }; B<T

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.180 (s). 11 q(s)