gpt4 book ai didi

c++ - 我应该如何进行这种显式特化?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:29:12 25 4
gpt4 key购买 nike

下面的设计是否可行?

template <typename T>
class Test{
public:
template <typename Z>
void doSomething();
//rest of things
private:
T obj;
//some things
};

现在,如果可能的话,我会为 doSomething 做一些明确的特化,这样最后我会得到如下所示的一些版本:

void doSomething<int>(){
//do something
}
void doSomething<double>(){
//do something
}
...etc

这似乎是不可能的,我找不到任何语法来完成这项工作,然后我想也许设计应该如下所示,以便所有模板参数都应该传递给模板类本身:

template <typename T,typename Z>
class Test{
public:
void doSomething();
//rest of things
private:
T obj;
//some things
};

然后我尝试了甚至没有编译的部分特化:

template <typename T>
void Test<T,int>::doSomething(){
//do something
}
template <typename T>
void Test<T,double>::doSomething(){
//do something
}
...etc

对于显式特化,我得到了以下错误:
错误#1:类模板名称后的模板参数列表必须按照模板参数列表中使用的顺序列出参数。
错误 #2:“Container1”:模板参数太少。

最佳答案

为了显式特化doSomething,您还必须显式特化Test

从 14.7.3/18 开始:

In an explicit specialization declaration for a member of a class template or a member template that appears in namespace scope, the member template and some of its enclosing class templates may remain unspecialized, except that the declaration shall not explicitly specialize a class member template if its enclosing class templates are not explicitly specialized as well.

关于c++ - 我应该如何进行这种显式特化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4274828/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com