好吧,我相信在 c++11 之前,你注定要手动提供推论......你可以为此创建专门化的辅助结构:
template <typename A, typename B>
struct deduce { };
template <>
struct deduce<int, double> {
typedef double type;
};
template <typename ScalarL, typename ScalarR>
struct Multi
{
typename deduce<ScalarL, ScalarR>::type operator()(ScalarL input1, ScalarR input2) const
{
return input1 * input2;
}
};
int main(){
Multi<int, double> mt;
mt(1,2.0);
}
编辑:
更通用的方法是调用创建在推导结果类型时应考虑的类型的优先级层次结构。示例代码:
#include <iostream>
template <typename T>
struct MoreGeneralNumber { };
template <>
struct MoreGeneralNumber<long>: MoreGeneralNumber<int> {};
template <>
struct MoreGeneralNumber<float>: MoreGeneralNumber<long> {};
template <>
struct MoreGeneralNumber<double>: MoreGeneralNumber<float> {};
typedef char (&yes)[1];
typedef char (&no)[2];
template <bool L, bool R, typename LT, typename RT>
struct MoreGeneral { };
template <bool R, typename LT, typename RT>
struct MoreGeneral<true, R, LT, RT> {
typedef LT type;
};
template <typename LT, typename RT>
struct MoreGeneral<false, true, LT, RT> {
typedef RT type;
};
template <typename B, typename D>
struct Host
{
operator B*() const;
operator D*();
};
template <typename B, typename D>
struct is_base_of
{
template <typename T>
static yes check(D*, T);
static no check(B*, int);
static const bool value = sizeof(check(Host<B,D>(), int())) == sizeof(yes);
};
template <typename L, typename R>
struct Deduce: MoreGeneral<is_base_of<MoreGeneralNumber<R>, MoreGeneralNumber<L> >::value,
is_base_of<MoreGeneralNumber<L>, MoreGeneralNumber<R> >::value, L, R > {
};
template <typename ScalarL, typename ScalarR>
struct Multi
{
typename Deduce<ScalarL, ScalarR>::type operator()(ScalarL input1, ScalarR input2) const
{
return input1 * input2;
}
};
int main() {
Multi<int, double> mt;
std::cout << mt(1, 2.5) << std::endl;
}