I have a class
that I use for purely syntactic purposes, to call a function in a certain way. This is a simplified example:
#include<iostream>
template<class T1>
struct make{
template<class T2>
static T1 from(T2 const& t2){
return T1{}; //or something more complicated
}
};
int main(){
double d = make<double>::from(2);
std::cout << d << '\n';
}
Now, suppose I want to warn the user that this class should not be instantiated. There may be uses for the class to be instatiable but I have the curiosity if it is possible to forbid that?
First I tried deleting the default constructor
template<class T1>
struct make{
make() = delete;
template<class T2>
static T1 from(T2 const& t2){
return T1{}; //or something more complicated
}
};
But then this is still possible:
make<double> m{}; // valid
Finally, I tried deleting the destructor and that seemed to work
template<class T1>
struct make{
~make() = delete;
template<class T2>
static T1 from(T2 const& t2){
return T1{}; //or something more complicated
}
};
But it seems that then the class can still be allocated by new
.
Should I delete both the destructor and the delete constructor, (what about the copy and move constructor?)
Is this the best way to disallow instantiation? code here: http://ift.tt/2bhjo8H
#include<iostream>
template<class T1>
struct make{
make() = delete;
~make() = delete;
template<class T2>
static T1 from(T2 const& t2){
return T1{}; //or something more complicated
}
};
int main(){
double d = make<double>::from(2);
std::cout << d << '\n';
make<double> m{}; // compile error (no destructor)
auto p = new make<double>{}; // compile error (no constructor)
}
Aucun commentaire:
Enregistrer un commentaire