C++构造函数的模板特化
我有一个模板类 A
template <typename T, int M> class A;
typedef A<std::string, 20> one_type;
typedef A<std::string, 30> second_type;
template <typename T, int M>
class A {
public:
A(int m) {test= (m>M);}
bool test;
};
template<>
one_type::one_type() { cerr << "One type" << endl;}
我想要 A 类
I have a templated class A<T, int> and two typedefs A<string, 20> and A<string, 30>.
How do I override the constructor for A<string, 20> ? The following does not work:
template <typename T, int M> class A;
typedef A<std::string, 20> one_type;
typedef A<std::string, 30> second_type;
template <typename T, int M>
class A {
public:
A(int m) {test= (m>M);}
bool test;
};
template<>
one_type::one_type() { cerr << "One type" << endl;}
I would like the class A<std::string,20> to do something that the other class doesn't. How can I do this without changing the constructor A:A(int) ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
迟到但非常优雅的解决方案:
C++ 2020 引入了约束和概念。您现在可以有条件地启用和禁用构造函数和析构函数!
在此处运行代码。
Late but a very elegant solution:
C++ 2020 introduced Constraints and Concepts. You can now conditionally enable and disable constructors and destructors!
Run the code here.
您唯一不能做的就是使用
typedef
来定义构造函数。除此之外,您应该像这样专门化A
构造函数:如果您希望
A
有一个不同的< /em> 构造函数而不是通用的A
,您需要专门化整个A
类:The only thing you cannot do is use the
typedef
to define the constructor. Other than that, you ought to specialize theA<string,20>
constructor like this:If you want
A<string,20>
to have a different constructor than the genericA
, you need to specialize the wholeA<string,20>
class:假设您的确实意味着
A::test
可以公开访问,您可以这样做:踢一下轮胎:
Assuming your really meant for
A::test
to be publicly accessible, you could do something like this:Kick the tires:
这可能有点晚了,但是如果您可以访问
c++11
,您可以使用 SFINAE 来完成你想要的:工作示例
This may be a little bit late, but if you have access to
c++11
you can use SFINAE to accomplish just what you want:Working example
怎么样:
How about :
您目前的方法无法做到这一点。 one_type 是特定模板专业化的别名,因此它获取模板具有的任何代码。
如果要添加特定于 one_type 的代码,则必须将其声明为 A 专业化的子类,如下所示:
You can't with your current approach. one_type is an alias to a particular template specialization, so it gets whatever code the template has.
If you want to add code specific to one_type, you have to declare it as a subclass of A specialization, like this:
对于这种情况,我能想到的最佳解决方案是使用“构造函数辅助函数”:
The best solution I've been able to come up with for this situation is to use a "constructor helper function":