小编Sip*_*pka的帖子

根据其他模板参数指定返回类型

我想通过其他模板参数指定模板化函数的返回类型。所有这些都在一个班级中。

在头文件中:

class MyClass {
    template<int type, typename RT>
    RT myfunc();
};
Run Code Online (Sandbox Code Playgroud)

在 .cpp 中是这样的:

template<>
int MyClass::myfunc<1, int>() { return 2; }

template<>
double MyClass::myfunc<2, double>() { return 3.14; }

template<>
const char* MyClass::myfunc<3, const char*>() { return "some string"; }
Run Code Online (Sandbox Code Playgroud)

我希望能够像这样使用我的功能:

MyClass m;
int i = m.myfunc<1>(); // i will be 2
double pi = m.myfunc<2>(); // pi will be 3.14
const char* str = m.myfunc<3>(); // str == "some string"
Run Code Online (Sandbox Code Playgroud)

所以我希望我的函数能够通过一个模板整数(或任何枚举)进行参数化,并且基于这个整数,返回类型会有所不同。我不希望该函数使用指定参数以外的任何其他整数参数,例如这里m.myfunc<4>()会产生编译错误。

我只想通过一个模板参数来参数化我的函数,因为它m.myfunc<1, int>()可以工作,但我不想一直写类型名。 …

c++ templates return-type function-templates

5
推荐指数
1
解决办法
1588
查看次数

为什么方法抛出而不是返回null?

我想知道为什么有些方法会抛出Exception而不是返回null

例如Class.forName(String className)方法抛出ClassNotFoundException.如果被调用者想要通知我们为什么不返回null,我们可以用a检查结果if,而不必写try-catch块.

为什么不写这个:

try{
    Class<?> c = Class.forName("foo.Bar");
} catch(ClassNotFoundException e){
    ...
}
Run Code Online (Sandbox Code Playgroud)

像这样:

Class<?> c = Class.forName("foo.Bar");
if(c != null) {
    ...
} else {
    //handle that class wasn't found
}
Run Code Online (Sandbox Code Playgroud)

Exceptions当可能有特定值返回(最好null或有时-1)时,为什么要使用,以通知调用者操作失败?我知道,如果一个方法可能会失败更多的方式,调用者可以在反应中以错误信息分开来,但在这种情况下,ClassNotFoundException只有当类找不到抛出.

而且还有性能问题,返回的速度要快null于抛出Exception不是吗?

java exception throw

0
推荐指数
1
解决办法
124
查看次数