我有一个class
纯语法目的,以某种方式调用函数。这是一个简化的例子:
#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';
}
现在,假设我想警告用户不应实例化此类。该类可能有一些用途,但我很好奇是否可以禁止它?
首先我尝试删除默认构造函数
template<class T1>
struct make{
make() = delete;
template<class T2>
static T1 from(T2 const& t2){
return T1{}; //or something more complicated
}
};
但这仍然是可能的:
make<double> m{}; // valid
最后,我尝试删除析构函数,这似乎有效
template<class T1>
struct make{
~make() = delete;
template<class T2>
static T1 from(T2 const& t2){
return T1{}; //or something more complicated
}
};
但似乎那时该类仍然可以由new
.
我应该同时删除析构函数和删除构造函数吗(复制和移动构造函数呢?)
这是禁止实例化的最佳方法吗?代码在这里:http ://coliru.stacked-crooked.com/a/0299c377c129fffb
#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)
}