Search Results

Search found 3493 results on 140 pages for 'constructor'.

Page 18/140 | < Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >

  • Specializing a class template constructor

    - by SilverSun
    I'm messing around with template specialization and I ran into a problem with trying to specialize the constructor based on what policy is used. Here is the code I am trying to get to work. #include <cstdlib> #include <ctime> class DiePolicies { public: class RollOnConstruction { }; class CallMethod { }; }; #include <boost/static_assert.hpp> #include <boost/type_traits/is_same.hpp> template<unsigned sides = 6, typename RollPolicy = DiePolicies::RollOnConstruction> class Die { // policy type check BOOST_STATIC_ASSERT(( boost::is_same<RollPolicy, DiePolicies::RollOnConstruction>::value || boost::is_same<RollPolicy, DiePolicies::CallMethod>::value )); unsigned m_die; unsigned random() { return rand() % sides; } public: Die(); void roll() { m_die = random(); } operator unsigned () { return m_die + 1; } }; template<unsigned sides> Die<sides, DiePolicies::RollOnConstruction>::Die() : m_die(random()) { } template<unsigned sides> Die<sides, DiePolicies::CallMethod>::Die() : m_die(0) { } ...\main.cpp(29): error C3860: template argument list following class template name must list parameters in the order used in template parameter list ...\main.cpp(29): error C2976: 'Die' : too few template arguments ...\main.cpp(31): error C3860: template argument list following class template name must list parameters in the order used in template parameter list Those are the errors I get in Microsoft Visual Studio 2010. I'm thinking either I can't figure out the right syntax for the specialization, or maybe it isn't possible to do it this way.

    Read the article

  • Unity Framework constructor parameters in MVC

    - by ubersteve
    I have an ASP.NET MVC3 site that I want to be able to use different types of email service, depending on how busy the site is. Consider the following: public interface IEmailService { void SendEmail(MailMessage mailMessage); } public class LocalEmailService : IEmailService { public LocalEmailService() { // no setup required } public void SendEmail(MailMessage mailMessage) { // send email via local smtp server, write it to a text file, whatever } } public class BetterEmailService : IEmailService { public BetterEmailService (string smtpServer, string portNumber, string username, string password) { // initialize the object with the parameters } public void SendEmail(MailMessage mailMessage) { //actually send the email } } Whilst the site is in development, all of my controllers will send emails via the LocalEmailService; when the site is in production, they will use the BetterEmailService. My question is twofold: 1) How exactly do I pass the BetterEmailService constructor parameters? Is it something like this (from ~/Bootstrapper.cs): private static IUnityContainer BuildUnityContainer() { var container = new UnityContainer(); container.RegisterType<IEmailService, BetterEmailService>("server name", "port", "username", "password"); return container; } 2) Is there a better way of doing that - i.e. putting those keys in the web.config or another configuration file so that the site would not need to be recompiled to switch which email service it was using? Many thanks!

    Read the article

  • Cannot exit in CodeIgniter constructor

    - by gzg
    I'm basically trying a session control. If the user is logged in, it's ok to move on. But if he's not logged in, then it will show a log-in screen and then die. However, when I use die or exit in the constructor, it does not show the log-in screen; it immediately dies. The code is as following: private $username = null; private $mongoid = null; private $neoid = null; public function __construct(){ parent::__construct(); // session to global $this->username = $this->session->userdata( 'username'); $this->mongoid = $this->session->userdata( 'mongoid'); $this->neoid = $this->session->userdata( 'neoid'); // check if user is logged in if( $this->username == "" || empty( $this->username)){ $this->load->view( 'access/login'); die; } } It shows the log-in page if die is not written there, but with die, it does not show. Why do I want to use die? Because if I don't use, it moves on the index function and I don't want it to execute index function if the user is not logged in. What is wrong here? What should I use to stop executing?

    Read the article

  • named type not used for constructor injection

    - by nmarun
    Hi, I have a simple console application where I have the following setup: public interface ILogger { void Log(string message); } class NullLogger : ILogger { private readonly string version; public NullLogger() { version = "1.0"; } public NullLogger(string v) { version = v; } public void Log(string message) { Console.WriteLine("NULL " + version + " : " + message); } } The configuration details are below: <type type="UnityConsole.ILogger, UnityConsole" mapTo="UnityConsole.NullLogger, UnityConsole"> My calling code looks as below: IUnityContainer container = new UnityContainer(); UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity"); section.Containers.Default.Configure(container); ILogger nullLogger = container.Resolve(); nullLogger.Log("hello"); This works fine, but once I give a name to this type something like: <type type="UnityConsole.ILogger, UnityConsole" mapTo="UnityConsole.NullLogger, UnityConsole" name="NullLogger"> The above calling code does not work even if I explicitly register the type using container.RegisterType<ILogger, NullLogger>(); I get the error: {"Resolution of the dependency failed, type = \"UnityConsole.ILogger\", name = \"\". Exception message is: The current build operation (build key Build Key[UnityConsole.NullLogger, null]) failed: The parameter v could not be resolved when attempting to call constructor UnityConsole.NullLogger(System.String v). (Strategy type BuildPlanStrategy, index 3)"} Why doesn't unity look into named instances? To get it to work, I'll have to do: ILogger nullLogger = container.Resolve("NullLogger"); Where is this behavior documented? Arun

    Read the article

  • C++ Template Class Constructor with Variable Arguments

    - by david
    Is it possible to create a template function that takes a variable number of arguments, for example, in this Vector< T, C class constructor: template < typename T, uint C > Vector< T, C >::Vector( T, ... ) { assert( C > 0 ); va_list arg_list; va_start( arg_list, C ); for( uint i = 0; i < C; i++ ) { m_data[ i ] = va_arg( arg_list, T ); } va_end( arg_list ); } This almost works, but if someone calls Vector< double, 3 ( 1, 1, 1 ), only the first argument has the correct value. I suspect that the first parameter is correct because it is cast to a double during the function call, and that the others are interpreted as ints and then the bits are stuffed into a double. Calling Vector< double, 3 ( 1.0, 1.0, 1.0 ) gives the desired results. Is there a preferred way to do something like this?

    Read the article

  • C++: calling member functions within constructor?

    - by powerboy
    The following code raises a runtime error: #include <iostream> #include <iterator> #include <ext/slist> class IntList : public __gnu_cxx::slist<int> { public: typedef IntList::iterator iterator; IntList() { tail_ = begin(); } // seems that there is a problem here void append(const int node) { tail_ = insert_after(tail_, node); } private: iterator tail_; }; int main() { IntList list; list.append(1); list.append(2); list.append(3); for (IntList::iterator i = list.begin(); i != list.end(); ++i) { std::cout << *i << " "; } return 0; } Seems that the problem is in the constructor IntList(). Is it because it calls the member function begin()?

    Read the article

  • Passing System classes as constructor parameters

    - by mcl
    This is probably crazy. I want to take the idea of Dependency Injection to extremes. I have isolated all System.IO-related behavior into a single class so that I can mock that class in my other classes and thereby relieve my larger suite of unit tests of the burden of worrying about the actual file system. But the File IO class I end up with can only be tested with integration tests, which-- of course-- introduces complexity I don't really want to deal with when all I really want to do is make sure my FileIO class calls the correct System.IO stuff. I don't need to integration test System.IO. My FileIO class is doing more than simply wrapping System.IO functions, every now and then it does contain some logic (maybe this is the problem?). So what I'd like is to be able to test my File IO class to ensure that it makes the correct system calls by mocking the System.IO classes themselves. Ideally this would be as easy as having a constructor like so: public FileIO( System.IO.Directory directory, System.IO.File file, System.IO.FileStream fileStream ) { this.Directory = directory; this.File = file; this.FileStream = fileStream; } And then calling in methods like: public GetFilesInFolder(string folderPath) { return this.Directory.GetFiles(folderPath) } But this doesn't fly since the System.IO classes in question are static classes. As far as I can tell they can neither be instantiated in this way or subclassed for the purposes of mocking.

    Read the article

  • no default constructor exists for class

    - by MixedCoder
    #include "Includes.h" enum BlowfishAlgorithm { ECB, CBC, CFB64, OFB64, }; class Blowfish { public: struct bf_key_st { unsigned long P[18]; unsigned long S[1024]; }; Blowfish(BlowfishAlgorithm algorithm); void Dispose(); void SetKey(unsigned char data[]); unsigned char Encrypt(unsigned char buffer[]); unsigned char Decrypt(unsigned char buffer[]); char EncryptIV(); char DecryptIV(); private: BlowfishAlgorithm _algorithm; unsigned char _encryptIv[200]; unsigned char _decryptIv[200]; int _encryptNum; int _decryptNum; }; class GameCryptography { public: Blowfish _blowfish; GameCryptography(unsigned char key[]); void Decrypt(unsigned char packet[]); void Encrypt(unsigned char packet[]); Blowfish Blowfish; void SetKey(unsigned char k[]); void SetIvs(unsigned char i1[],unsigned char i2[]); }; GameCryptography::GameCryptography(unsigned char key[]) { } Error:IntelliSense: no default constructor exists for class "Blowfish" ???!

    Read the article

  • Building a structure/object in a place other than the constructor

    - by Vishal Naidu
    I have different types of objects representing the same business entity. UIObject, PowershellObject, DevCodeModelObject, WMIObject all are different representation to the same entity. So say if the entity is Animal then I have AnimalUIObject, AnimalPSObject, AnimalModelObject, AnimalWMIObject, etc. Now the implementations of AnimalUIObject, AnimalPSObject, AnimalModelObject are all in separate assemblies. Now my scenario is I want to verify the contents of business entity Animal irrespective of the assembly it came from. So I created a GenericAnimal class to represent the Animal entity. Now in GenericAnimal I added the following constructors: GenericAnimal(AnimalUIObject) GenericAnimal(AnimalPSObject) GenericAnimal(AnimalModelObject) Basically I made GenericAnimal depend on all the underlying assemblies so that while verifying I deal with this abstraction. Now the other approach to do this is have GenericAnimal with an empty constructor an allow these underlying assemblies to have a Transform() method which would build the GenericAnimal. Both approaches have some pros and cons: The 1st approach: Pros: All construction logic is in one place in one class GenericAnimal Cons: GenericAnimal class must be touched every-time there is a new representation form. The 2nd approach: Pros: construction responsibility is delegated to the underlying assembly. Cons: As construction logic is spread accross assemblies, tomorrow if I need to add a property X in GenericAnimal then I have to touch all the assemblies to change the Transform method. Which approach looks better ? or Which would you consider a lesser evil ? Is there any alternative way better than the above two ?

    Read the article

  • std::thread and class constructor and destructor

    - by toeplitz
    When testing threads in C++11 I have created the following example: #include <iostream> #include <thread> class Foo { public: Foo(void) { std::cout << "Constructor called: " << this << std::endl; } ~Foo(void) { std::cout << "Destructor called: " << this << std::endl; } void operator()() const { std::cout << "Operatior called: " << this << std::endl; } }; void test_normal(void) { std::cout << "====> Standard example:" << std::endl; Foo f; } void test_thread(void) { std::cout << "====> Thread example:" << std::endl; Foo f; std::thread t(f); t.detach(); } int main(int argc, char **argv) { test_normal(); test_thread(); for(;;); } Which prints the following: Why is the destructor called 6 times for the thread? And why does the thread report different memory locations?

    Read the article

  • Using Reflection.Emit to match existing constructor

    - by yodaj007
    First, here is the C# code and the disassembled IL: public class Program<T> { private List<T> _items; public Program(T x, [Microsoft.Scripting.ParamDictionary] Microsoft.Scripting.IAttributesCollection col) { _items = new List<T>(); _items.Add(x); } } Here is the IL of that constructor: .method public hidebysig specialname rtspecialname instance void .ctor(!T x, class [Microsoft.Scripting]Microsoft.Scripting.IAttributesCollection col) cil managed { .param [2] .custom instance void [Microsoft.Scripting]Microsoft.Scripting.ParamDictionaryAttribute::.ctor() = ( 01 00 00 00 ) // Code size 34 (0x22) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: nop IL_0008: ldarg.0 IL_0009: newobj instance void class [mscorlib]System.Collections.Generic.List`1<!T>::.ctor() IL_000e: stfld class [mscorlib]System.Collections.Generic.List`1<!0> class Foo.Program`1<!T>::_items IL_0013: ldarg.0 IL_0014: ldfld class [mscorlib]System.Collections.Generic.List`1<!0> class Foo.Program`1<!T>::_items IL_0019: ldarg.1 IL_001a: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<!T>::Add(!0) IL_001f: nop IL_0020: nop IL_0021: ret } // end of method Program`1::.ctor I am trying to understand the IL code by emitting it myself. This is what I have managed to emit: .method public hidebysig specialname rtspecialname instance void .ctor(!T A_1, class [Microsoft.Scripting]Microsoft.Scripting.IAttributesCollection A_2) cil managed { // Code size 34 (0x22) .maxstack 4 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: newobj instance void class [mscorlib]System.Collections.Generic.List`1<!T>::.ctor() IL_000c: stfld class [mscorlib]System.Collections.Generic.List`1<!0> class MyType<!T>::_items IL_0011: ldarg.0 IL_0012: ldfld class [mscorlib]System.Collections.Generic.List`1<!0> class MyType<!T>::_items IL_0017: ldarg.s A_1 IL_0019: nop IL_001a: nop IL_001b: nop IL_001c: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<!T>::Add(!0) IL_0021: ret } // end of method MyType::.ctor There are a few differences that I just can't figure out. I'm really close... How do I take care of the parameter attribute (ParamDictionaryAttribute)? I can't find a 'custom' opcode. Is the .param [2] important? How do I emit that? Why is the C# code stack size 8, while my emitted version is 4? Is this important?

    Read the article

  • F# Add Constructor to a Record?

    - by akaphenom
    Basically I want to have a single construct to deal with serializing to both JSON and formatted xml. Records workd nicley for serializing to/from json. However XmlSerializer requires a parameterless construtor. I don't really want to have to go through the exercise of building class objects for these constructs (principal only). I was hoping there could be some shortcut for getting a parameterless constructor onto a record (perhaps with a wioth statement or something). I can't get it to behave - has anybody in the community had any luck? module JSONExample open System open System.IO open System.Net open System.Text open System.Web open System.Xml open System.Security.Authentication open System.Runtime.Serialization //add assemnbly reference System.Runtime.Serialization System.Xml open System.Xml.Serialization open System.Collections.Generic [<DataContract>] type ChemicalElementRecord = { [<XmlAttribute("name")>] [<field: DataMember(Name="name") >] Name:string [<XmlAttribute("name")>] [<field: DataMember(Name="boiling_point") >] BoilingPoint:string [<XmlAttribute("atomic-mass")>] [<field: DataMember(Name="atomic_mass") >] AtomicMass:string } [<XmlRoot("freebase")>] [<DataContract>] type FreebaseResultRecord = { [<XmlAttribute("code")>] [<field: DataMember(Name="code") >] Code:string [<XmlArrayAttribute("results")>] [<XmlArrayItem(typeof<ChemicalElementRecord>, ElementName = "chemical-element")>] [<field: DataMember(Name="result") >] Result: ChemicalElementRecord array [<XmlElement("message")>] [<field: DataMember(Name="message") >] Message:string } let getJsonFromWeb() = let query = "[{'type':'/chemistry/chemical_element','name':null,'boiling_point':null,'atomic_mass':null}]" let query = query.Replace("'","\"") let queryUrl = sprintf "http://api.freebase.com/api/service/mqlread?query=%s" "{\"query\":"+query+"}" let request : HttpWebRequest = downcast WebRequest.Create(queryUrl) request.Method <- "GET" request.ContentType <- "application/x-www-form-urlencoded" let response = request.GetResponse() let result = try use reader = new StreamReader(response.GetResponseStream()) reader.ReadToEnd(); finally response.Close() let data = Encoding.Unicode.GetBytes(result); let stream = new MemoryStream() stream.Write(data, 0, data.Length); stream.Position <- 0L stream let test = // get some JSON from the web let stream = getJsonFromWeb() // convert the stream of JSON into an F# Record let JsonSerializer = Json.DataContractJsonSerializer(typeof<FreebaseResultRecord>) let result: FreebaseResultRecord = downcast JsonSerializer.ReadObject(stream) // save the Records to disk as JSON use fs = new FileStream(@"C:\temp\freebase.json", FileMode.Create) JsonSerializer.WriteObject(fs,result) fs.Close() // save the Records to disk as System Controlled XML let xmlSerializer = DataContractSerializer(typeof<FreebaseResultRecord>); use fs = new FileStream(@"C:\temp\freebase.xml", FileMode.Create) xmlSerializer.WriteObject(fs,result) fs.Close() use fs = new FileStream(@"C:\temp\freebase-pretty.xml", FileMode.Create) let xmlSerializer = XmlSerializer(typeof<FreebaseResultRecord>) xmlSerializer.Serialize(fs,result) fs.Close() ignore(test)

    Read the article

  • Copy constructor bug

    - by user168715
    I'm writing a simple nD-vector class, but am encountering a strange bug. I've stripped out the class to the bare minimum that still reproduces the bug: #include <iostream> using namespace std; template<unsigned int size> class nvector { public: nvector() {data_ = new double[size];} ~nvector() {delete[] data_;} template<unsigned int size2> nvector(const nvector<size2> &other) { data_ = new double[size]; int i=0; for(; i<size && i < size2; i++) data_[i] = other[i]; for(; i<size; i++) data_[i] = 0; } double &operator[](int i) {return data_[i];} const double&operator[](int i) const {return data_[i];} private: const nvector<size> &operator=(const nvector<size> &other); //Intentionally unimplemented for now double *data_; }; int main() { nvector<2> vector2d; vector2d[0] = 1; vector2d[1] = 2; nvector<3> vector3d(vector2d); for(int i=0; i<3; i++) cout << vector3d[i] << " "; cout << endl; //Prints 1 2 0 nvector<3> other3d(vector3d); for(int i=0; i<3; i++) cout << other3d[i] << " "; cout << endl; //Prints 1 2 0 } //Segfault??? On the surface this seems to work fine, and both tests print out the correct values. However, at the end of main the program crashes with a segfault, which I've traced to nvector's destructor. At first I thought the (incorrect) default assignment operator was somehow being called, which is why I added the (currently) unimplemented explicit assignment operator to rule this possibility out. So my copy constructor must be buggy, but I'm having one of those days where I'm staring at extremely simple code and just can't see it. Do you guys have any ideas?

    Read the article

  • factory class, wrong number of arguments being passed to subclass constructor

    - by Hugh Bothwell
    I was looking at Python: Exception in the separated module works wrong which uses a multi-purpose GnuLibError class to 'stand in' for a variety of different errors. Each sub-error has its own ID number and error format string. I figured it would be better written as a hierarchy of Exception classes, and set out to do so: class GNULibError(Exception): sub_exceptions = 0 # patched with dict of subclasses once subclasses are created err_num = 0 err_format = None def __new__(cls, *args): print("new {}".format(cls)) # DEBUG if len(args) and args[0] in GNULibError.sub_exceptions: print(" factory -> {} {}".format(GNULibError.sub_exceptions[args[0]], args[1:])) # DEBUG return super(GNULibError, cls).__new__(GNULibError.sub_exceptions[args[0]], *(args[1:])) else: print(" plain {} {}".format(cls, args)) # DEBUG return super(GNULibError, cls).__new__(cls, *args) def __init__(self, *args): cls = type(self) print("init {} {}".format(cls, args)) # DEBUG self.args = args if cls.err_format is None: self.message = str(args) else: self.message = "[GNU Error {}] ".format(cls.err_num) + cls.err_format.format(*args) def __str__(self): return self.message def __repr__(self): return '{}{}'.format(type(self).__name__, self.args) class GNULibError_Directory(GNULibError): err_num = 1 err_format = "destination directory does not exist: {}" class GNULibError_Config(GNULibError): err_num = 2 err_format = "configure file does not exist: {}" class GNULibError_Module(GNULibError): err_num = 3 err_format = "selected module does not exist: {}" class GNULibError_Cache(GNULibError): err_num = 4 err_format = "{} is expected to contain gl_M4_BASE({})" class GNULibError_Sourcebase(GNULibError): err_num = 5 err_format = "missing sourcebase argument: {}" class GNULibError_Docbase(GNULibError): err_num = 6 err_format = "missing docbase argument: {}" class GNULibError_Testbase(GNULibError): err_num = 7 err_format = "missing testsbase argument: {}" class GNULibError_Libname(GNULibError): err_num = 8 err_format = "missing libname argument: {}" # patch master class with subclass reference # (TO DO: auto-detect all available subclasses instead of hardcoding them) GNULibError.sub_exceptions = { 1: GNULibError_Directory, 2: GNULibError_Config, 3: GNULibError_Module, 4: GNULibError_Cache, 5: GNULibError_Sourcebase, 6: GNULibError_Docbase, 7: GNULibError_Testbase, 8: GNULibError_Libname } This starts out with GNULibError as a factory class - if you call it with an error number belonging to a recognized subclass, it returns an object belonging to that subclass, otherwise it returns itself as a default error type. Based on this code, the following should be exactly equivalent (but aren't): e = GNULibError(3, 'missing.lib') f = GNULibError_Module('missing.lib') print e # -> '[GNU Error 3] selected module does not exist: 3' print f # -> '[GNU Error 3] selected module does not exist: missing.lib' I added some strategic print statements, and the error seems to be in GNULibError.__new__: >>> e = GNULibError(3, 'missing.lib') new <class '__main__.GNULibError'> factory -> <class '__main__.GNULibError_Module'> ('missing.lib',) # good... init <class '__main__.GNULibError_Module'> (3, 'missing.lib') # NO! ^ why? I call the subclass constructor as subclass.__new__(*args[1:]) - this should drop the 3, the subclass type ID - and yet its __init__ is still getting the 3 anyway! How can I trim the argument list that gets passed to subclass.__init__?

    Read the article

  • Unity The parameter host could not be resolved when attempting to call constructor

    - by Terrance
    When I attempt to instantiate my instance of the base class I get the error: a ResolutionFailedException with roughly the following error "The parameter host could not be resolved when attempting to call constructor" I'm currently not using an Interface for the base type and my instance of the class is inheriting the base type class. I'm new to Unity and DI so I'm thinking its something I forgot possibly. ExeConfigurationFileMap map = new ExeConfigurationFileMap(); map.ExeConfigFilename = "Unity.Config"; Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None); UnityConfigurationSection section = (UnityConfigurationSection)config.GetSection("unity"); IUnityContainer container = new UnityContainer(); section.Containers.Default.Configure(container); //Throws exception here on this BaseCalculatorServer server = container.Resolve<BaseCalculatorServer>(); and the Unity.Config file <container> <types> <type name ="CalculatorServer" type="Calculator.Logic.BaseCalculatorServer, Calculator.Logic" mapTo="Calculator.Logic.CalculateApi, Calculator.Logic"/> </types> </container> </containers> The Base class using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Transactions; using Microsoft.Practices.Unity; using Calculator.Logic; namespace Calculator.Logic { public class BaseCalculatorServer : IDisposable { public BaseCalculatorServer(){} public CalculateDelegate Calculate { get; set; } public CalculationHistoryDelegate CalculationHistory { get; set; } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { this.Dispose(); } } } The Implementation using System; using System.Collections.Generic; using System.Linq; using System.Text; using Calculator.Logic; using System.ServiceModel; using System.ServiceModel.Configuration; using Microsoft.Practices.Unity; namespace Calculator.Logic { public class CalculateApi:BaseCalculatorServer { public CalculateApi(ServiceHost host) { host.Open(); Console.WriteLine("Press Enter To Exit"); Console.ReadLine(); host.Close(); } public CalculateDelegate Calculate { get; set; } public CalculationHistoryDelegate CalculationHistory { get; set; } } } Yes both base class and implementation are in the same Namespace and thats something design wise that will change once I get this working. Oh and a more detailed error Resolution of the dependency failed, type = "Calculator.Logic.BaseCalculatorServer", name = "". Exception message is: The current build operation (build key Build Key[Calculator.Logic.BaseCalculatorServer, null]) failed: The value for the property "Calculate" could not be resolved. (Strategy type BuildPlanStrategy, index 3)

    Read the article

  • Difficulty creating classes and arrays of those classes C#

    - by Lucifer Fayte
    I'm trying to implement a Discrete Fourier Transformation algorithm for a project I'm doing in school. But creating a class is seeming to be difficult(which it shouldn't be). I'm using Visual Studio 2012. Basically I need a class called Complex to store the two values I get from a DFT; The real portion and the imaginary portion. This is what I have so far for that: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SoundEditor_V3 { public class Complex { public double real; public double im; public Complex() { real = 0; im = 0; } } } The problem is that it doesn't recognize the constructor as a constructor, now I'm just learning C#, but I looked it up online and this is how it's supposed to look apparently. It recognizes my constructor as a method. Why is that? Am I creating the class wrong? It's doing the same thing for my Fourier class as well. So each time I try to create a Fourier object and then use it's method...there is no such thing. example, I do this: Fourier fou = new Fourier(); fou.DFT(s, N, amp, 0); and it tells me fou is a 'field' but is used like a 'type' why is it saying that? Here is the code for my Fourier class as well: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SoundEditor_V3 { public class Fourier { //FOURIER //N = number of samples //s is the array of samples(data) //amp is the array where the complex result will be written to //start is the where in the array to start public void DFT(byte[] s, int N, ref Complex[] amp, int start) { Complex tem = new Complex(); int f; int t; for (f = 0; f < N; f++) { tem.real = 0; tem.im = 0; for (t = 0; t < N; t++) { tem.real += s[t + start] * Math.Cos(2 * Math.PI * t * f / N); tem.im -= s[t + start] * Math.Sin(2 * Math.PI * t * f / N); } amp[f].real = tem.real; amp[f].im = tem.im; } } //INVERSE FOURIER public void IDFT(Complex[] A, ref int[] s) { int N = A.Length; int t, f; double result; for (t = 0; t < N; t++) { result = 0; for (f = 0; f < N; f++) { result += A[f].real * Math.Cos(2 * Math.PI * t * f / N) - A[f].im * Math.Sin(2 * Math.PI * t * f / N); } s[t] = (int)Math.Round(result); } } } } I'm very much stuck at the moment, any and all help would be appreciated. Thank you.

    Read the article

  • C++ templated factory constructor/de-serialization

    - by KRao
    Hi, I was looking at the boost serialization library, and the intrusive way to provide support for serialization is to define a member function with signature (simplifying): class ToBeSerialized { public: //Define this to support serialization //Notice not virtual function! template<class Archive> void serialize(Archive & ar) {.....} }; Moreover, one way to support serilization of derived class trough base pointers is to use a macro of the type: //No mention to the base class(es) from which Derived_class inherits BOOST_CLASS_EXPORT_GUID(Derived_class, "derived_class") where Derived_class is some class which is inheriting from a base class, say Base_class. Thanks to this macro, it is possible to serialize classes of type Derived_class through pointers to Base_class correctly. The question is: I am used in C++ to write abstract factories implemented through a map from std::string to (pointer to) functions which return objects of the desired type (and eveything is fine thanks to covariant types). Hover I fail to see how I could use the above non-virtual serialize template member function to properly de-serialize (i.e. construct) an object without knowing its type (but assuming that the type information has been stored by the serializer, say in a string). What I would like to do (keeping the same nomenclature as above) is something like the following: XmlArchive xmlArchive; //A type or archive xmlArchive.open("C:/ser.txt"); //Contains type information for the serialized class Base_class* basePtr = Factory<Base_class>::create("derived_class",xmlArchive); with the function on the righ-hand side creating an object on the heap of type Derived_class (via default constructor, this is the part I know how to solve) and calling the serialize function of xmlArchive (here I am stuck!), i.e. do something like: Base_class* Factory<Base_class>::create("derived_class",xmlArchive) { Base_class* basePtr = new Base_class; //OK, doable, usual map string to pointer to function static_cast<Derived_class*>( basePtr )->serialize( xmlArchive ); //De-serialization, how????? return basePtr; } I am sure this can be done (boost serialize does it but its code is impenetrable! :P), but I fail to figure out how. The key problem is that the serialize function is a template function. So I cannot have a pointer to a generic templated function. As the point in writing the templated serialize function is to make the code generic (i.e. not having to re-write the serialize function for different Archivers), it does not make sense then to have to register all the derived classes for all possible archive types, like: MY_CLASS_REGISTER(Derived_class, XmlArchive); MY_CLASS_REGISTER(Derived_class, TxtArchive); ... In fact in my code I relies on overloading to get the correct behaviour: void serialize( XmlArchive& archive, Derived_class& derived ); void serialize( TxtArchive& archive, Derived_class& derived ); ... The key point to keep in mind is that the archive type is always known, i.e. I am never using runtime polymorphism for the archive class...(again I am using overloading on the archive type). Any suggestion to help me out? Thank you very much in advance! Cheers

    Read the article

  • Requring static class setter to be called before constructor, bad design?

    - by roverred
    I have a class, say Foo, and every instance of Foo will need and contain the same List object, myList. Since every class instance will share the same List Object, I thought it would be good to make myList static and use a static function to set myList before the constructor is called. I was wondering if this was bad, because this requires the setter to be called before the constructor? If the person doesn't, the program will crash. Alternative way would be passing myList every time.

    Read the article

  • Why `A & a = a` is valid?

    - by psaghelyi
    #include <iostream> #include <assert.h> using namespace std; struct Base { Base() : m_member1(1) {} Base(const Base & other) { assert(this != &other); // this should trigger m_member1 = other.m_member1; } int m_member1; }; struct Derived { Derived(Base & base) : m_base(m_base) {} // m_base(base) Base & m_base; }; void main() { Base base; Derived derived(base); cout << derived.m_base.m_member1 << endl; // crashes here } The above example is a synthesized version of a mistyped constructor. I used reference at the class member Derived::m_base because I wanted to make sure that the member will be initialized as the constructor had called. One problem is that nor GCC nor MSVC gives me a warning at m_base(m_base). But the more serious for me is that the assert finds everything fine and the application crashes later (sometimes far away from the mistake). Question: Is there any way to indicate such mistakes?

    Read the article

  • get and set for class in model - MVC 2 asp.net

    - by bergin
    Hi there, I want to improve the program so it has a proper constructor but also works with the models environment of MVC. I currently have: public void recordDocument(int order_id, string filename, string physical_path, string slug, int bytes) { ArchiveDocument doc = new ArchiveDocument(); doc.order_id = order_id; doc.filename = filename; doc.physical_path = physical_path; doc.slug = slug; doc.bytes = bytes; db.ArchiveDocuments.InsertOnSubmit(doc); } This obviously should be a constructor and should change to the leaner: public void recordDocument(ArchiveDocument doc) { db.ArchiveDocuments.InsertOnSubmit(doc); } with a get & set somewhere else - not sure of the syntax - do I create a partial class? so: creating in the somewhere repository - ArchiveDocument doc = new ArchiveDocument(order_id, idTaggedFilename, physical_path, slug, bytes); and then: namespace ordering.Models { public partial class ArchiveDocument { int order_id, string filename, string physical_path, string slug, int bytes; public archiveDocument(int order_id, string filename, string physical_path, string slug, int bytes){ this.order_id = order_id; etc } } How should I alter the code?

    Read the article

  • Java: using generic wildcards with subclassing

    - by gibberish
    Say I have a class Foo, a class A and some subclass B of A. Foo accepts A and its sublclasses as the generic type. A and B both require a Foo instance in their constructor. I want A's Foo to be of type A , and B's Foo to be of type B or a superclass of B. So in effect, So I only want this: Foo<X> bar = new Foo<X>; new B(bar); to be possible if X is either A, B, or a both subclass of A and superclass of B. So far this is what I have: class Foo<? extends A>{ //construct } class A(Foo<A> bar){ //construct } class B(Foo<? super B> bar){ super(bar); //construct } The call to super(...) doesn't work, because <A> is stricter than <? super B>. Is it somehow possible to use the constructor (or avoid code duplication by another means) while enforcing these types? Edit: Foo keeps a collection of elements of the generic parameter type, and these elements and Foo have a bidirectional link. It should therefore not be possible to link an A to a Foo.

    Read the article

  • C++: Construction and initialization order guarantees

    - by Helltone
    Hi, I have some doubts about construction and initialization order guarantees in C++. For instance, the following code has four classes X, Y, Z and W. The main function instantiates an object of class X. X contains an object of class Y, and derives from class Z, so both constructors will be called. Additionally, the const char* parameter passed to X's constructor will be implicitly converted to W, so W's constructor must also be called. What are the guarantees the C++ standard gives on the order of the calls to the copy constructors? Or, equivalently, this program is allowed to print? #include <iostream> class Z { public: Z() { std::cout << "Z" << std::endl; } }; class Y { public: Y() { std::cout << "Y" << std::endl; } }; class W { public: W(const char*) { std::cout << "W" << std::endl; } }; class X : public Z { public: X(const W&) { std::cout << "X" << std::endl; } private: Y y; }; int main(int, char*[]) { X x("x"); return 0; }

    Read the article

  • Why would one want to use the public constructors on Boolean and similar immutable classes?

    - by Robert J. Walker
    (For the purposes of this question, let us assume that one is intentionally not using auto(un)boxing, either because one is writing pre-Java 1.5 code, or because one feels that autounboxing makes it too easy to create NullPointerExceptions.) Take Boolean, for example. The documentation for the Boolean(boolean) constructor says: Note: It is rarely appropriate to use this constructor. Unless a new instance is required, the static factory valueOf(boolean) is generally a better choice. It is likely to yield significantly better space and time performance. My question is, why would you ever want to get a new instance in the first place? It seems like things would be simpler if constructors like that were private. For example, if they were, you could write this with no danger (even if myBoolean were null): if (myBoolean == Boolean.TRUE) It'd be safe because all true Booleans would be references to Boolean.TRUE and all false Booleans would be references to Boolean.FALSE. But because the constructors are public, someone may have used them, which means that you have to write this instead: if (Boolean.TRUE.equals(myBoolean)) But where it really gets bad is when you want to check two Booleans for equality. Something like this: if (myBooleanA == myBooleanB) ...becomes this: if ( (myBooleanA == null && myBooleanB == null) || (myBooleanA == null && myBooleanA.equals(myBooleanB)) ) I can't think of any reason to have separate instances of these objects which is more compelling than not having to do the nonsense above. What say you?

    Read the article

  • error: no matching function for call to ‘BSTreeNode<int, int>::BSTreeNode(int, int, NULL, NULL)’ - what's wrong?

    - by Alexander Suraphel
    error: no matching function for call to ‘BSTreeNode::BSTreeNode(int, int, NULL, NULL)’ candidates are: BSTreeNode::BSTreeNode(KF, DT&, BSTreeNode*, BSTreeNode*) [with KF = int, DT = int] here is how I used it: BSTreeNode<int, int> newNode(5,9, NULL, NULL) ; I defined it as follows: BSTreeNode(KF sKey, DT &data, BSTreeNode *lt, BSTreeNode *rt):key(sKey),dataItem(data), left(lt), right(rt){} what's wrong with using my constructor this way? i've been pulling out my hair all night please help me ASAP!!

    Read the article

  • Boost singleton and restricted

    - by Ockonal
    Hello, I'm using boost singleton from thread/detail. There is in manual, that constructor should have signlature: boost::restricted. But I can't find any reference for this type in boost library. Why do I need in this and where I can find it?

    Read the article

< Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >