禁用函数的基于参数的模板参数推导的更好方法? [英] Better way to disable argument-based template parameter deduction for functions?

查看:26
本文介绍了禁用函数的基于参数的模板参数推导的更好方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我想要做的:

template <typename T> void f(DisableDeduction<T> obj) {std::cout << obj;}
// Here DisableDeduction<T> aliases T, but in a such way
// that would prevent compiler from deducing T based
// on provided argument.

/* ... */

f<int>(1); // Works.
f(1); // Error, can't deduce template parameter based on argument.

这是我目前实现它的方式:

This is how I currently achieve it:

template <typename T> struct DisableDeduction_Internal {using type = T;};
template <typename T> using DisableDeduction = typename DisableDeduction_Internal<T>::type;

它工作得很好(如上所述),但它引入了一种额外的辅助类型.

It works perfectly (as described), but it introduces one extra helper type.

但是我可以在没有额外类型的情况下获得相同的结果吗?

推荐答案

你可以把 T 放在不可推论的上下文中(在 :: 的左边),并使用 std::common_type 来自 .

You can do it by putting T in non deducible context (to the left of ::), and use std::common_type from <type_traits>.

示例:

template <typename T> void f(typename std::common_type<T>::type obj) {std::cout << obj;}

这篇关于禁用函数的基于参数的模板参数推导的更好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆