相同模板参数的专业化

时间:2012-12-27 17:25:07

标签: c++ templates

我有一个功能模板:

//the most generalized template 
template<typename typeArg, typename typeRet>
typeRet func(const typeArg &val);

和它的几个专业,看起来像:

template<>
someType func(const otherType &val)
{
    //code
}

template<>
typeFoo func(const typeBar &val)
{
    //more code
}

但它没有默认实现。

显然,这两种类型都无法自动推断,因此调用如下:

type1 var1 = func<argType,type1>(arg);

仅在类型相同的情况下编写默认实现的正确方法是什么?

我尝试了一些变种:

第一次尝试

template<typename theOnlyType, theOnlyType>
theOnlyType func(const typeArg &theOnlyType)
{
    //code
}

但这是错误的,因为这个函数只有一个模板参数,并且它与上面的调用不对应。

第二次尝试

template<typename type1, typename type2>
type1 func(const type1 &theOnlyType)
{
    //code
}

调用变得模棱两可,候选者是这个函数,是第一个代码块中最通用的模板。

1 个答案:

答案 0 :(得分:3)

经过一番研究后,我想出了一个明显更好的解决方案。它涉及在静态方法周围添加一个包装类,并通过全局方法调度它们:

#include <iostream>

namespace tag
{
    template <typename U, typename P>
    struct wrapper // default implementation
    {
        static U foo(P const &)
        {
            std::cout << "different types";
            return U();
        }
    };
}

namespace tag
{
    template <typename T>
    struct wrapper<T, T> // specialized
    {
        static T foo(T const &)
        {
            std::cout << "same type";
            return T();
        }
    };
}

template <typename U, typename P>
static inline U foo(P const &p)
{
    return tag::wrapper<U, P>::foo(p);
}

int main()
{
    foo<int>(0);
    foo<int>(true);
}

我希望这会有所帮助。


std::enable_ifstd::is_same一起使用(C ++ 11):

template <typename A, typename B, typename = 
          typename std::enable_if<std::is_same<A, B>::value>::type> 
B foo(const A &) {

}

或者将此版本用于C ++ 03及更早版本:

template <typename A, typename B> struct foo; // implement for different types

template <typename T> struct foo<T, T> {
    T operator()(const T &) {
        // default impelentation
    }
};

int main() {

    foo<int, int> f;
    int n;

    f( n );

}

我确信有办法改善这一点。我试图对函数使用部分特化,但我无法让它为我工作。

相关问题