我有一个功能,现在可以为我返回某种类型的值。看起来像这样
@RuntimePermissions
public class MainActivity extends AppCompatActivity {
@NeedsPermission(Manifest.permission.CAMERA)
void showCamera() {
getSupportFragmentManager().beginTransaction()
.replace(R.id.sample_content_fragment, CameraPreviewFragment.newInstance())
.addToBackStack("camera")
.commitAllowingStateLoss();
}
@OnShowRationale(Manifest.permission.CAMERA)
void showRationaleForCamera(final PermissionRequest request) {
new AlertDialog.Builder(this)
.setMessage(R.string.permission_camera_rationale)
.setPositiveButton(R.string.button_allow, (dialog, button) -> request.proceed())
.setNegativeButton(R.string.button_deny, (dialog, button) -> request.cancel())
.show();
}
@OnPermissionDenied(Manifest.permission.CAMERA)
void showDeniedForCamera() {
Toast.makeText(this, R.string.permission_camera_denied, Toast.LENGTH_SHORT).show();
}
@OnNeverAskAgain(Manifest.permission.CAMERA)
void showNeverAskForCamera() {
Toast.makeText(this, R.string.permission_camera_neverask, Toast.LENGTH_SHORT).show();
}
}
这有效,但我不喜欢它在运行时解析,而不是编译时间,但这允许我做
template<typename T>
T getNullValue(){
if(std::is_same<T,long long>::value){
return NULL_LONG;
}else if(std::is_same<T,double>::value){
return NULL_DOUBLE;
}
}
我怎样才能这样做,以便我可以根据我想要返回的内容重载不同版本的getNullValue,而无需在运行时解决它。
double x = getNullValue<double>();
long long y = getNullValue<long long>();
答案 0 :(得分:1)
模板专业化应该很好地完成。优化编译器应将其转换为简单赋值。
// getNullValue.hpp :
template <class T>
T getNullValue() {
return 0;
}
// remember to declare specialization in header or strange linking errors may occur
template <> long long getNullValue<long long>()
template <> double getNullValue<double>()
// getNullValue.cpp:
template <> long long getNullValue<long long>() {
return NULL_LONG;
}
template <> double getNullValue<double>() {
return NULL_DOUBLE;
}
int main() {
double x = getNullValue<double>();
long long y = getNullValue<long long>();
}
有关专业化的更多示例,请参阅http://en.cppreference.com/w/cpp/language/template_specialization。